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

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

相关推荐
程序员老刘10 小时前
Android Studio Quail 4发布,看日志我以为谷歌放弃Flutter了
flutter·android studio·ai编程
Crazy_MT11 小时前
Flutter 本地大模型实战:做一个自然语言记账工具
flutter·llm·ai编程
嵩风抚17 小时前
一款HK银行APP的业务+技术
android·flutter·react native·html5
00后程序员张19 小时前
怎么用 Egret(白鹭引擎)打包 iOS 应用并上架 App Store?
android·ios·小程序·https·uni-app·iphone·webview
不羁的木木19 小时前
给鸿蒙 App 增加广播收发能力 —— flutter_broadcasts 的鸿蒙使用指南
flutter·harmonyos
不羁的木木20 小时前
给鸿蒙 App 增加打开外部网页能力 —— flutter_web_browser 的鸿蒙使用指南
前端·flutter·harmonyos
安好说AI21 小时前
Flutter 三方库 sound_mode 的鸿蒙化适配指南:免权限读取与受限写入的契约对齐
flutter·harmonyos·鸿蒙
●VON21 小时前
Flutter 鸿蒙 disk_space_2 1.0.13 使用实战:下载前检查磁盘空间
flutter·华为·harmonyos·鸿蒙
●VON1 天前
Flutter 鸿蒙插件适配实战:用 device_screen_brightness 2.0.0 控制并监听屏幕亮度
flutter·华为·harmonyos
风早爽太2 天前
Flutter 开发笔记:share_plus 分享插件
笔记·flutter