我有一个较长的输入表单,用户可以在其中添加许多相同的子表单。
例如想一想父母可以输入数据的表格(父母表格),然后添加孩子。由于我不知道用户有多少个孩子,他们可以使用按钮动态添加更多的孩子表单。
对于每个孩子,请求的数据都是相同的,例如名称,生日,性别,实际上大约有10个字段。所以我创建了一个单独的小部件(子窗体)。
如果用户现在保存了外部表单,则需要从子表单中收集所有信息。现在,我可以通过在父窗体内创建所有TextController,将它们保存在列表中并在创建子窗体时插入它们来完成此操作,如下所示:
void addTextField() {
int index = _childNameControllers.length;
_childNameControllers.add( TextEditingController());
_childforms.add(
RemovableEntityField(
nameController: _childNameControllers[index]
)
);
}
然后保存类似
的内容void onSave() {
List<Childs> _childs = [];
_childNameControllers.forEach((controller) {
if (controller.text.trim().isNotEmpty) {
_childs.add(Child(name: name));
}
});
// do something with the data
}
但是正如我说的那样,每个子表单我大约有10个字段,我必须为每个表单创建10个控制器,并且在子表单中需要10个参数才能读取此信息。
有更简单的方法吗?
PS:我知道我可以将儿童州设为公开州,但我也不想这么做
答案 0 :(得分:2)
我相信您应该在子级中添加变量updater并将值推高到父级。
https://github.com/flutter/flutter/tree/master/examples/stocks
扑扑的股票应用程序有一个例子。
在孩子中,您需要这个。
class StockSettings extends StatefulWidget {
const StockSettings(this.configuration, this.updater);
final StockConfiguration configuration;
final ValueChanged<StockConfiguration> updater;
@override
StockSettingsState createState() => StockSettingsState();
}
class StockSettingsState extends State<StockSettings> {
void _handleBackupChanged(bool value) {
sendUpdates(widget.configuration.copyWith(backupMode: value ? BackupMode.enabled : BackupMode.disabled));
}
void sendUpdates(StockConfiguration value) {
if (widget.updater != null)
widget.updater(value);
}
在父级中,您传递了configuartion更新器,它只是围绕设置状态的包装器
class StocksAppState extends State<StocksApp> {
StockData stocks;
StockConfiguration _configuration = StockConfiguration(
stockMode: StockMode.optimistic,
backupMode: BackupMode.enabled,
debugShowGrid: false,
debugShowSizes: false,
debugShowBaselines: false,
debugShowLayers: false,
debugShowPointers: false,
debugShowRainbow: false,
showPerformanceOverlay: false,
showSemanticsDebugger: false
);
@override
void initState() {
super.initState();
stocks = StockData();
}
void configurationUpdater(StockConfiguration value) {
setState(() {
_configuration = value;
});
}
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => StockHome(stocks, _configuration, configurationUpdater),
'/settings': (BuildContext context) => StockSettings(_configuration, configurationUpdater)
},