如何从另一个文件调用setstate?

时间:2020-02-26 20:33:50

标签: flutter state

我上课了:

class FavoritesState extends State<Favorites> {
  var configOk = isConfigLoaded;
  @override
  Widget build(BuildContext context) {
    if (configOk) {
      return Padding(
        padding: EdgeInsets.only(top: 10),
        child: ListView.builder(
          itemCount: stationList.length,
          itemBuilder: (context, position) {
            return StationCard(stationList[position]);
          },
        ),
      );
    } else {
      return LoadingScreen();
    }
  }

  void callback() {
    setState(() {
      this.configOk = true;
    });
  }
}

我有方法:

Future<http.Response> getConfig() async {
    //Load Config 
    isConfigLoaded = true;
}

最后,我需要此方法在收藏夹状态中调用setstate并在那里上载信息。我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:0)

如果只更新一次小部件的状态,则也可以使用FutureBuildergetConfig()调用完成后,FutureBuilder将强制您的小部件重新构建。 这样可以简化事情:

class Favorites extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getConfig(),
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          // display the loading screen as long as your getConfig() call hasn't finished
          return LoadingScreen();
        }
        return Padding(
          padding: EdgeInsets.only(top: 10),
          child: ListView.builder(
            itemCount: stationList.length,
            itemBuilder: (context, position) {
              return StationCard(stationList[position]);
            },
          ),
        );
      },
    );
  }
}

然后将您的呼叫调整为以下内容:

Future<http.Response> getConfig() async {
  //Load Config

  // return your result
  return result;
}