Flutter FutureBuilder

FutureBuilderis a widget in Flutter for Futurebuilding user interfaces based on the results of . It takes a Futureobject and a constructor as parameters.

FutureBuilderwill listen for Futurechanges to the object and update the UI accordingly. A loading indicator can be displayed while Futurethe is being parsed. Once Futurecomplete, the build function is called to process the returned data and build the UI based on success or failure status.

Here is FutureBuilderan example using :

Future<String> fetchData() async {
  // 模拟异步调用
  await Future.delayed(Duration(seconds: 2));
  return "数据加载成功";
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: fetchData(),
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          // 在等待 Future 完成时显示加载指示器
          return CircularProgressIndicator();
        } else {
          if (snapshot.hasError) {
            // 处理错误情况
            return Text('错误:${snapshot.error}');
          } else {
            // 数据已经成功获取
            return Text('数据:${snapshot.data}');
          }
        }
      },
    );
  }
}

In this example, fetchDataa function represents an asynchronous operation that returns a string value Future. FutureBuilderPass this Futurealong with a builder function to define how to Futurebuild the UI based on the different states. In this example, we display a loading indicator while the data is loading, display an error message if there is an error, or display the fetched data if it was fetched successfully.

Guess you like

Origin blog.csdn.net/qq_27981847/article/details/131602112
Recommended