Created
August 17, 2022 17:20
-
-
Save justinmc/1ed6f6a2faa3bf5dc0a6ce83119afeeb to your computer and use it in GitHub Desktop.
An example of getting all field values in a Form.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/material.dart'; | |
| void main() => runApp(MyApp()); | |
| class MyApp extends StatelessWidget { | |
| @override | |
| Widget build(BuildContext context) { | |
| return MaterialApp( | |
| title: 'Flutter Demo', | |
| debugShowCheckedModeBanner: false, | |
| theme: ThemeData( | |
| primarySwatch: Colors.blue, | |
| ), | |
| home: MyHomePage(title: 'Flutter Demo Home Page'), | |
| ); | |
| } | |
| } | |
| class MyHomePage extends StatelessWidget { | |
| MyHomePage({ | |
| Key? key, | |
| required this.title, | |
| }) : super(key: key); | |
| final String title; | |
| final GlobalKey<FormState> _formKey = GlobalKey(); | |
| final List<GlobalKey> _fieldKeys = <GlobalKey>[ | |
| GlobalKey(), | |
| GlobalKey(), | |
| GlobalKey(), | |
| GlobalKey(), | |
| ]; | |
| void _onPressed() { | |
| final FormState? formState = _formKey.currentState; | |
| if (formState == null || !formState.validate() == true) return; | |
| // With submit: | |
| // final data = formState.submit(); | |
| // final newPost = Post.fromJson(data); | |
| // Without submit: | |
| final Map<GlobalKey, dynamic> data = <GlobalKey, dynamic>{}; | |
| for (GlobalKey fieldKey in _fieldKeys) { | |
| final FormFieldState<dynamic> formFieldState = fieldKey.currentState as FormFieldState<dynamic>; | |
| if (formFieldState.value != null) { | |
| data[fieldKey] = formFieldState.value; | |
| } | |
| } | |
| print('data: $data'); | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| title: Text(title), | |
| ), | |
| body: Center( | |
| child: Form( | |
| key: _formKey, | |
| child: SingleChildScrollView( | |
| child: Column( | |
| crossAxisAlignment: CrossAxisAlignment.start, | |
| children: _fieldKeys.map((GlobalKey fieldKey) { | |
| return TextFormField( | |
| key: fieldKey, | |
| ); | |
| }).toList(), | |
| ), | |
| ), | |
| ), | |
| ), | |
| floatingActionButton: FloatingActionButton( | |
| onPressed: _onPressed, | |
| tooltip: 'Increment', | |
| child: const Icon(Icons.add), | |
| ), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment