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
学习记录,每天不停进步。