如果我的flutter应用程序中有10个Text字段,那么我必须制作10个Text Editing Controller来控制这些字段,比如从它们那里获取文本。但是,有可能在我的应用程序中会有几百个TextField,那么,我是否要像下面提到的代码一样,制作100个TextEditingControllers呢?如果不是,那么最好的解决方法是什么?
import 'package:flutter/material.dart';
class TestScreen extends StatefulWidget {
@override
_TestScreenState createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
final TextEditingController firstController = TextEditingController();
final TextEditingController secondController = TextEditingController();
final TextEditingController thirdController = TextEditingController();
final TextEditingController fourthController = TextEditingController();
final TextEditingController fifthController = TextEditingController();
final TextEditingController sixthController = TextEditingController();
final TextEditingController seventhController = TextEditingController();
final TextEditingController eightController = TextEditingController();
final TextEditingController ninthController = TextEditingController();
final TextEditingController tenthController = TextEditingController();
@override
Widget build(BuildContext context) {
return Container(
child: Form(
child: Column(
children: <Widget>[
TextFormField(
controller: firstController,
),
TextFormField(
controller: secondController,
),
TextFormField(
controller: thirdController,
),
TextFormField(
controller: fourthController,
),
TextFormField(
controller: fifthController,
),
TextFormField(
controller: sixthController,
),
TextFormField(
controller: seventhController,
),
TextFormField(
controller: eightController,
),
TextFormField(
controller: ninthController,
),
TextFormField(
controller: tenthController,
),
],
),
),
);
}
}
处理多个 TextFormField
在flutter中,我们可以使用一个叫做 Form
只有一个 GlobalKey
中的所有数据进行检查和保存。TextFormField
.
我想解释一下,但是,我相信......。 读这本扑朔迷离的食谱 你会明白很多
编辑
由于我看到有一些疑惑,我简单的解释一下如何保存数据,那将是下一步的那个菜谱。
Form
附带 GlobalKey
如烹饪手册中所解释的那样。_formKey.currentState.validate()
和 validator
每个 TextFormField
.TextFormField
使用_formKey.currentState.save()
和 onSaved
财产。该 TextFormField
会是这样的。
TextFormField(
decoration: const InputDecoration(
hintText: 'What do people call you?',
labelText: 'Name *',
),
onSaved: (String value) {
// Use this code to save the text wherever you need it, a Map, List, db...
},
validator: (String value) {
if (value.contains('@') {
return 'Do not use the @ char.';
}
return null;
},
)
希望对你有帮助!