一尘不染

使用FutureBuilder时重新加载数据

flutter

我正在加载小部件时的数据,如下面的代码。UI完全加载后,我想添加一个刷新按钮以再次重新加载数据。

如何刷新视图?

  class _MyHomePageState extends State<MyHomePage> {

      @override
      Widget build(BuildContext context) {
        var futureBuilder = new FutureBuilder(
          future: _getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return new Text('loading...');
              default:
                if (snapshot.hasError)
                  return new Text('Error: ${snapshot.error}');
                else
                  return createListView(context, snapshot);
            }
          },
        );

        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Home Page"),
          ),
          body: futureBuilder,
        );
      }

      Future<List<String>> _getData() async {
        var values = new List<String>();

        await new Future.delayed(new Duration(seconds: 5));

        return values;
      }

      Widget createListView(BuildContext context, AsyncSnapshot snapshot) {

      }
    }

阅读 1239

收藏
2020-08-13

共1个答案

一尘不染

Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
  RaisedButton button = RaisedButton(onPressed: () {
    setState(() {});
  }, child: Text('Refresh'),);
  //.. here create widget with snapshot data and with necessary button
}
2020-08-13