flutter - Flutter - 在 FutureBuilder 中等待 setState 然后加载组件
问题描述
我正在尝试类似的东西。在 Future Builder 中加载服务,设置文本字段值,然后编写组件。
final data = FutureBuilder(
future: DatameterService.getMapData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
setState(() {
calleController.text = snapshot.data.calle;
paisController.text = snapshot.data.pais;
provinciaController.text = snapshot.data.provincia;
poblacionController.text = snapshot.data.poblacion;
postalController.text = snapshot.data.postal;
});
return form;
} else {
return indicator;
}
但是返回
在构建期间调用 setState() 或 markNeedsBuild()。
所以问题是:如何使用 FutureBuilder 填充 TextField 输入值?
解决方案
You should never call setState
in build, and the reason is simple: setState causes a build, and build calls setState - you're in an infinite loop. That's why the engine tells you explicitly that you shouldn't try to do this.
In fact, you should not be doing any business logic inside build. From your code, it looks like you wanna load some data when the page appears and set some initial fields to your TextField
s. I don't think you want to be using a FutureBuilder
here, since you have a StatefulWidget
. Instead, you can move the future out of the build and have it be called in initState
.
Something like this:
class _MyState extends State<MyWidget> {
Map<String, dynamic> _data;
bool _loading;
TextEditingController _controller;
@override
void initState() {
super.initState();
// start fetching
_loading = true;
_data = {};
_controller = TextEditingController();
getData().then((data) {
setState(() {
_data = data;
_loading = false;
_controller.text = _data['text'];
});
});
}
Widget build(BuildContext context) {
// handle loading vs. not loading
if (_loading) return CircularProgressIndicator();
return Container(
// the rest of your code
);
}
}
You don't really even need to store _data
but it could be useful for resetting the forms or something.
推荐阅读
- python - Tkinter,有两个独立的板子可以参考
- javascript - 不使用模板时 res.redirect 不起作用
- javascript - 如何使用 sinon 单元测试 redux saga spawn 功能
- linker - 如何使用 clang 将 crtbegin.o 和 crtend.o 链接到我的 32 位操作系统
- java - Spring JUnit 5 无法检测到用于测试的默认配置类?
- python - 测试套件失败后如何防止snakemake停止?
- r - 在 R 中将 case 组合到 cumsum 计算中的问题
- python - 如何在保存 Django 模型表单之前将数据更新到相关字段
- delphi - 编译有问题。Delphi 似乎可以编译,但编译后的应用程序没有反映所做的更改
- bash - 添加 awk 命令 bash 脚本