首页 > 解决方案 > 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 输入值?

标签: flutter

解决方案


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 TextFields. 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.


推荐阅读