我正在制作一个包含多个TextFields(例如大于12)的数据收集应用程序。我正在使用Form键来验证所有这些应用程序。我想要所有文本字段的值,以便可以将它们保存到firestore。我该怎么做呢?这是我的代码:
TextField
import 'package:flutter/material.dart'; class MainForm extends StatefulWidget { @override _MainFormState createState() => _MainFormState(); } class _MainFormState extends State<MainForm> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Center( child: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: <Widget>[ Text('Enter information about PG Owner'), Padding( padding: const EdgeInsets.all(8.0), child: TextField( autofocus: true, textCapitalization: TextCapitalization.words, textAlignVertical: TextAlignVertical.center, onTap: () {}, decoration: InputDecoration( prefixIcon: Icon(Icons.face), labelText: 'Enter Name of Owner', border: OutlineInputBorder()), ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( validator: (value) { if (value.length < 15) { return 'Address seems very short!'; } return null; }, keyboardType: TextInputType.text, decoration: InputDecoration( prefixIcon: Icon(Icons.room), labelText: 'Enter full address of Owner', border: OutlineInputBorder()), ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( keyboardType: TextInputType.number, validator: (value) { if (value.length < 9) { return 'Phone number must be 9 digits or longer'; } return null; }, decoration: InputDecoration( prefixIcon: Icon(Icons.phone), labelText: 'Phone number of Owner', border: OutlineInputBorder()), ), ), Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( validator: (value) { if (value.isEmpty) { return 'Please enter a valid email address'; } if (!value.contains('@')) { return 'Email is invalid, must contain @'; } if (!value.contains('.')) { return 'Email is invalid, must contain .'; } return null; }, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( prefixIcon: Icon(Icons.mail_outline), labelText: 'Enter Email', border: OutlineInputBorder()), ), ), ) ], ), ), ), ); } }
更新:我知道从a获取值的正确方法(我已经阅读了文档)TextField是通过创建一个控制器。但是,就我而言,有14 TextFields要求我创建14个控制器。有更好的方法吗?
使用TextFormField中的控制器,您可以获取TextFormField的值。
TextEditingController emailEditingController = TextEditingController(); TextFormField( controller: emailEditingController, validator: (value) { if (value.isEmpty) { return 'Please enter a valid email address'; } if (!value.contains('@')) { return 'Email is invalid, must contain @'; } if (!value.contains('.')) { return 'Email is invalid, must contain .'; } return null; }, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( prefixIcon: Icon(Icons.mail_outline), labelText: 'Enter Email', border: OutlineInputBorder()), );
获得价值,例如:
String email=emailEditingController.text;
更新的答案
通过使用onSubmitted获得价值
onSubmitted: (String value){email=value;},