cpd_David_und_Yusuf/lib/main.dart

113 lines
3.0 KiB
Dart

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: UserDataForm(),
);
}
}
class UserDataForm extends StatefulWidget {
@override
_UserDataFormState createState() => _UserDataFormState();
}
class _UserDataFormState extends State<UserDataForm> {
final _formKey = GlobalKey<FormState>();
String _name = '';
int _age = 0;
double _height = 0.0;
void _submitData() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
// Zeigt einen Dialog mit den gespeicherten Daten
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Gespeicherte Daten'),
content: Text(
'Name: $_name\nAlter: $_age\nGröße: ${_height.toStringAsFixed(2)} m'),
actions: <Widget>[
TextButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Benutzerdaten-Formular'),
),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
onSaved: (value) {
_name = value!;
},
validator: (value) {
if (value!.isEmpty) {
return 'Bitte einen Namen eingeben';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Alter'),
keyboardType: TextInputType.number,
onSaved: (value) {
_age = int.parse(value!);
},
validator: (value) {
if (value!.isEmpty || int.tryParse(value) == null) {
return 'Bitte ein gültiges Alter eingeben';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Größe (in Metern)'),
keyboardType: TextInputType.numberWithOptions(decimal: true),
onSaved: (value) {
_height = double.parse(value!);
},
validator: (value) {
if (value!.isEmpty || double.tryParse(value) == null) {
return 'Bitte eine gültige Größe eingeben';
}
return null;
},
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: ElevatedButton(
onPressed: _submitData,
child: Text('Speichern und anzeigen'),
),
),
],
),
),
);
}
}