Skip to content

Instantly share code, notes, and snippets.

@stegrams
Last active June 2, 2020 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stegrams/badfe75b9ea2482ac5d28fb5a19bf89a to your computer and use it in GitHub Desktop.
Save stegrams/badfe75b9ea2482ac5d28fb5a19bf89a to your computer and use it in GitHub Desktop.
Show a form as custom dialog and collect the field values.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
@immutable
class CategoryModel {
const CategoryModel({this.name, this.keywords});
final String name;
final String keywords;
String toString() => 'CategoryModel{name:$name, keywords:$keywords}';
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
CategoryModel model = CategoryModel(name: '{Empty}', keywords: '{Empty}');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dialog Form'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('1.Show Dialog'),
onPressed: () async {
final result = await showDialog<CategoryModel>(
context: context,
builder: categoryDialogBuilder,
);
setState(() => model = result);
},
),
SizedBox(width: 5),
RaisedButton(
child: Text('2.Console Print'),
onPressed: () => print(model ?? 'User canceled'),
),
],
),
),
);
}
}
Widget categoryDialogBuilder(BuildContext context) {
String name = '';
String keywords = '';
GlobalKey<FormState> formKey = GlobalKey<FormState>();
return Dialog(
child: Form(
key: formKey,
child: ListView(
padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
shrinkWrap: true,
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
onSaved: (value) => name = value,
),
SizedBox(height: 10),
TextFormField(
decoration: InputDecoration(labelText: 'Keywords'),
onSaved: (value) => keywords = value,
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
RaisedButton(
child: Text('Ok'),
onPressed: () {
formKey.currentState.save();
Navigator.of(context).pop<CategoryModel>(
CategoryModel(
name: name,
keywords: keywords,
),
);
},
),
RaisedButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop<CategoryModel>();
},
),
],
)
],
),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment