initialize data once in initState and call the setState when data is ready causes exception

后端 未结 4 1522
清酒与你
清酒与你 2021-01-11 10:39

Since flutter calls the build method many times in different condition, to avoid getting the data many times, I initialize the data in initState.

I want

4条回答
  •  旧时难觅i
    2021-01-11 10:59

    I moved my code to my build method from initState and it worked

    class _TestState extends State {
    
      Data data;
      bool dataReady = false;
    
      @override
      void initState() {
        super.initState();
    
      }
    
      @override
      Widget build(BuildContext context) {
        getData(context).then((Data data) async {
          setState(() {
            dataReady= true;
          });
        });
        if (dataReady) {
          return createMainContent(context);
        } else {
          return new Container();
        }
      }
    
    }
    

提交回复
热议问题