flutter开发实战-使用FutureBuilder异步数据更新Widget

flutter开发实战-使用FutureBuilder异步数据更新Widget

在开发过程中,经常遇到需要依赖异步数据更新Widget的情况,如下载图片后显示Widget,获取到某个数据时候,显示在对应的UI界面上,都可以使用FutureBuilder异步数据更新Widget。

一、FutureBuilder

FutureBuilder是一个Widget,该Widget基于与Future]交互的最新快照构建的。

dart 复制代码
/// Creates a widget that builds itself based on the latest snapshot of
  /// interaction with a [Future].
  ///
  /// The [builder] must not be null.
  const FutureBuilder({
    super.key,
    this.future,
    this.initialData,
    required this.builder,
  }) : assert(builder != null);

其中

  • future:final Future? future; 是一个异步的任务;

  • builder:final AsyncWidgetBuilder builder;是创建显示的Widget,可以根据AsyncSnapshot<String?> snapshot来确定显示的Widget,可以在Future执行过程中被调用多次。

二、使用FutureBuilder

这里使用FutureBuilder的示例,我是通过加载网页时候,需要将Webview中设置cookie,cookie中需要设置token。token需要获取到再设置到Webview中的cookie中。

获取token

dart 复制代码
Future<String?> _getToken() async {
    final token = (await SessionDataService.sessionData)?.token;
    if (token == null) return null;
    return token;
  }

使用FutureBuilder用来在获取token后更新Webview,先判断snapshot.hasData是否有数据。如果有数据,则直接显示Webview,如果没有数据,则显示默认的Container。

dart 复制代码
FutureBuilder<String?>(
              future: _getToken(),
              builder: (BuildContext context, AsyncSnapshot<String?> snapshot) {
                if (snapshot.hasData) {
                  final token = snapshot.data;
                  if (token == null) return Container();

                  return WebView(
                    javascriptMode: JavascriptMode.unrestricted,
                    initialUrl: url,
                    initialCookies: [
                      WebViewCookie(
                          name: "auth", value: "token", domain: "inice.cn"),
                    ],
                    userAgent: "inice.cn",
                    onWebViewCreated: (controller) {
                      cookieManager.setCookies([
                        Cookie('auth', token)
                          ..domain = 'inice.cn'
                          ..httpOnly = false,
                      ]);
                      webController = controller;
                    },
                  );
                }
                return Container();
              },
            ),

完整代码如下

dart 复制代码
class WebViewScreen extends StatelessWidget {
  WebViewScreen({Key? key, required this.url}) : super(key: key);

  final String url;
  WebViewController? webController;

  final cookieManager = WebviewCookieManager();

  Future<String?> _getToken() async {
    // final token = (await SessionDataService.sessionData)?.token;
    final token = ApiAuth().token;
    if (token == null) return null;
    return token;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            color: Colors.amber,
          ),
          SafeArea(
            bottom: false,
            child: FutureBuilder<String?>(
              future: _getToken(),
              builder: (BuildContext context, AsyncSnapshot<String?> snapshot) {
                if (snapshot.hasData) {
                  final token = snapshot.data;
                  if (token == null) return Container();

                  return WebView(
                    javascriptMode: JavascriptMode.unrestricted,
                    initialUrl: url,
                    initialCookies: [
                      WebViewCookie(
                          name: "auth", value: "token", domain: "inice.cn"),
                    ],
                    userAgent: "inice.cn",
                    onWebViewCreated: (controller) {
                      cookieManager.setCookies([
                        Cookie('auth', token)
                          ..domain = 'inice.cn'
                          ..httpOnly = false,
                      ]);
                      webController = controller;
                    },
                  );
                }
                return Container();
              },
            ),
          ),
        ],
      ),
    );
  }
}

三、小结

flutter开发实战-使用FutureBuilder异步数据更新Widget。描述可能不是特别准确,请见谅。

https://blog.csdn.net/gloryFlow/article/details/133490457

学习记录,每天不停进步。

相关推荐
liulian091610 小时前
Flutter 网络状态与内容分享库:connectivity_plus 与 share_plus 的 OpenHarmony 适配指南
网络·flutter
toooooop811 小时前
aardio WebView 同源策略与跨域终极解决方案
webview·aardio
KKei163811 小时前
Flutter for OpenHarmony 学习视频播放器技术文章
学习·flutter·华为·音视频·harmonyos
KKei163812 小时前
Flutter for OpenHarmony 健身计划与运动打卡APP
flutter·华为·harmonyos
KKei163812 小时前
Flutter for OpenHarmony 在线考试与自测系统APP技术文章
flutter·华为·harmonyos
liulian091614 小时前
Flutter 依赖注入与设备信息库:get_it 与 device_info_plus 的 OpenHarmony 适配指南
flutter
KKei163815 小时前
Flutter for OpenHarmony学习目标追踪应用技术文章
学习·flutter·华为·harmonyos