我有一个较长的输入形式,其中用户可以添加若干相同子表单。
对于如想想一个表单,家长可以进入他们的数据(parentform),之后加入他们的孩子的。因为我不知道有多少孩子的一个用户,他们可以用一个按钮动态地添加更多的子窗体。
对于每个子请求的数据是相同的,从而例如姓名,生日,性别,在现实中它大约10场。所以我创建了一个单独的窗口小部件(childform)。
如果现在用户节省外在形式,我需要收集来自childforms的所有信息。我现在我可以通过创建parentform内的所有TextControllers做到这一点,将它们保存在一个名单,并且创造了childforms的时候,像这样插入它们:
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
}
但正如我说我每childform约10场,我必须创建10级控制器为每个表单,并需要在childform 10个参数只是读取这些信息。 是否有更简单的方法来做到这一点?
PS:我知道我可以让孩子状态公开,但我真的不希望做这一点
我相信你都应该在孩子添加变量更新,推动了价值高达父。
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);
}
在父,你传下去的配置更新这只是周围设置状态的包装
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)
},