18-flutter的Future和FutureBuilder
Future
表示接卸来某个时间的值或者错误,借助Future可以在flutter 总实现异步操作。
其本事是dart:async 包中的一个类,使用它的时候需要导入dart:async 包,Future 有两种状态。
- pending 执行中
- completed 执行结束 ,分为两种情况,要么成功并要么失败
1 异步操作
test() async{int result = await Future.delayed(Duration(milliseconds: 2000),(){return Future.value(123);});print('t3:' + DateTime.now().toString());print(result);}main(){print('t1:' + DateTime.now().toString());test();print('t2:' + DateTime.now().toString());}
// 打印结果如下 // flutter: t1:2019-08-25 15:32:32.880966
// flutter: t2:2019-08-25 15:32:33.054501
// flutter: t3:2019-08-25 15:32:35.059487
// flutter: 123
2 whenComplete
在future 结束的时候做一些事情
var random = Random();Future.delayed(Duration(seconds: 3),(){if (random.nextBool()){return 100;}else{throw 'ok';}}).then(print).catchError(print).whenComplete((){print('done');});
3 timeout
完成一个异步的操作需要很长时间,所以设置一个超市时间
main(){new Future.delayed(new Duration(seconds: 3),(){return 1;}).timeout(new Duration(seconds: 2)).then(print).catchError(print);}// TimeoutException after 0:00:02.000000: Future not completed
4 FutureBuilder
是一个将异步操作和异步UI 更新结合在一起的类,通过它我们可以将网络请求,数据库读取结果更新到页面上来。
构造方法
FutureBuilder({Key key, Future<T> future, T initialData, @required AsyncWidgetBuilder<T> builder })
future : Future对象表示此构建器当前连接的异步计算;
initialData: 表示一个非空的Future完成前的初始化数据;
builder: AsyncWidgetBuilder类型的回到函数,是一个基于异步交互构建widget的函数
- builder 函数接受两个参数
BuildContext context
与AsyncSnapshot<T> snapshot
,它返回一个widget。AsyncSnapshot
包含异步计算的信息,它具有以下属性: connectionState
- 枚举ConnectionState的值,表示与异步计算的连接状态,ConnectionState有四个值:none,waiting,active和done;data
- 异步计算接收的最新数据;error
- 异步计算接收的最新错误对象- AsyncSnapshot还具有
hasData
和hasError
属性,以分别检查它是否包含非空数据值或错误值。
- builder 函数接受两个参数
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;void main() => runApp(new MyApp());class MyApp extends StatefulWidget {@overrideState<StatefulWidget> createState() => _MyAppState();
}class _MyAppState extends State<MyApp> {String showResult = '';Future<CommonModel> fetchPost() async {final response = await http.get('http://www.devio.org/io/flutter_app/json/test_common_model.json');Utf8Decoder utf8decoder = Utf8Decoder(); //fix 中文乱码var result = json.decode(utf8decoder.convert(response.bodyBytes));return CommonModel.fromJson(result);}@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(appBar: AppBar(title: Text('Future与FutureBuilder实用技巧'),),body: FutureBuilder<CommonModel>(future: fetchPost(),builder:(BuildContext context, AsyncSnapshot<CommonModel> snapshot) {switch (snapshot.connectionState) {case ConnectionState.none:return new Text('Input a URL to start');case ConnectionState.waiting:return new Center(child: new CircularProgressIndicator());case ConnectionState.active:return new Text('');case ConnectionState.done:if (snapshot.hasError) {return new Text('${snapshot.error}',style: TextStyle(color: Colors.red),);} else {return new Column(children: <Widget>[Text('icon:${snapshot.data.icon}'), Text('statusBarColor:${snapshot.data.statusBarColor}'),Text('title:${snapshot.data.title}'),Text('url:${snapshot.data.url}')]);}}}),),);}
}class CommonModel {final String icon;final String title;final String url;final String statusBarColor;final bool hideAppBar;CommonModel({this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar});factory CommonModel.fromJson(Map<String, dynamic> json) {return CommonModel(icon: json['icon'],title: json['title'],url: json['url'],statusBarColor: json['statusBarColor'],hideAppBar: json['hideAppBar'],);}
}
相关文章:

js控制使div自动适应居中
一直都在想怎么样使弹出的DIV能在任何时候都是居中显示的,刚开始的时候是用CSS样式直接定义好层的位置,但是当页面很长的时候,或是浏览器窗口大小不是固定的时候就不能正确的显示,所以只好用JS来控制DIV的显示位置。首先再次详细解…

【poj3420】 Quad Tiling
http://poj.org/problem?id3420 (题目链接) 题意 给出$n*m$的网格,用$1*2$的方块覆盖有多少种方案。 Solution 数据很大,不能直接搞了,我们矩乘一下。0表示已放置,1表示未放置。dfs跑出一个$16*16$的转移矩阵,然后矩乘…

bokeh pandas_使用Pandas和Bokeh将Rolling Stone的500张最伟大专辑可视化
bokeh pandasby Gautham Koorma通过Gautham Koorma 使用Pandas和Bokeh将Rolling Stone的500张最伟大专辑可视化 (Rolling Stone’s 500 Greatest Albums Visualized Using Pandas and Bokeh) In 2003, Rolling Stones Magazine polled musicians, producers, and industry exe…

使用WinINet和WinHTTP实现Http訪问
使用WinINet和WinHTTP实现Http訪问 飘飘白云 l_zhaohui163.com 2007-11-30 Http訪问有两种方式,GET和POST,就编程来说GET方式相对简单点,它不用向server提交数据,在这个例程中我使用POST方式,提交数据value1与value2&a…

19-flutter的ListView 和 GridView的使用
ListView 的水平样式 和垂直样式 1 水平列表 import package:flutter/material.dart;const CITY_LIST ["北京","上海","广州","深圳","南京","郑州","武汉"];void main() > runApp(MyApp());clas…

linux下ndk编译命令行程序及配置
1.在http://developer.android.com/tools/sdk/ndk/index.html下载Android-ndk-r8e-linux-x86.tar.bz2,解压后把android-ndk-r8e添加到环境变量PATH中,例如, export PATH$PATH:/opt/studydisk/android-ndk-r8e 2.新建一个文件夹,如helloword&a…

vs2017数据可视化建模_介绍数据可视化社区调查2017
vs2017数据可视化建模by lars verspohl由拉斯韦斯波尔 介绍数据可视化社区调查2017 (Introducing the Data Visualization Community Survey 2017) Data visualization is a funny fish. It sort of stands on its own feet (or fins), but is also intimately entangled with…

20-flutter下拉刷新与上拉加载
1 RefreshIndicator 下拉刷新控件 下拉刷新的时候会回调 onRefresh 方法 RefreshIndicator(onRefresh: _handleRefresh,child: ListView(children: _buildList(),), ),2 上拉加载多 上拉加载更多的时候 override void initState() { super.initState();_scrollController.a…

PHP+redis实现超迷你全文检索
2014年10月31日 11:45:39 情景: 我们平台有好多游戏, 运营的同事在查询某一款游戏的时候, 目前使用的是html的select下拉列表的展现形式, 运营的同事得一个个去找,然后选中,耗时又费眼 效果: 输入"三国"或者"国三", 将自动列出所有包含"三国"的游…

Linux下的Shell编程(2)环境变量和局部变量
Shell Script是一种弱类型语言,使用变量的时候无需首先声明其类型。 局部变量在本地数据区分配内存进行存储,这个变量归当前的Shell所有,任何子进 程都不能访问本地变量。这些变量与环境变量不同,环境变量被存储在另一内存区&…

上拉电阻和下拉电阻_硬件基础:下拉电阻和上拉电阻如何工作
上拉电阻和下拉电阻by Taron Foxworth通过塔伦福克斯沃思(Taron Foxworth) 硬件基础:下拉电阻和上拉电阻如何工作 (Hardware fundamentals: how pull-down and pull-up resistors work) If you’ve ever wired up a button to an Arduino, you’ve come across thi…

时间序列学习笔记4
6. 重采样及频率转换 重采样(resample)表示将时间序列的频率进行转换的过程。可以分为降采样和升采样等。 pandas对象都有一个resample方法,可以进行频率转换。 In [5]: rng pd.date_range(1/1/2000, periods100, freqD)In [6]: ts Series(…

linux驱动编程入门实例
编辑 /*****hello.c*******/ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init() { printk("<1>hello\n"); return 0; } static void hello…

iOS UIView快速添加事件
给UIView 做一个延展 // // UIViewSKTap.h // MeiGouYouPin // // Created by coder on 2019/10/29. // Copyright © 2019 AlexanderYeah. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef void(^TapBlock)(void); interfac…

node.js中模块_在Node.js中需要模块:您需要知道的一切
node.js中模块by Samer Buna通过Samer Buna 在Node.js中需要模块:您需要知道的一切 (Requiring modules in Node.js: Everything you need to know) Update: This article is now part of my book “Node.js Beyond The Basics”.更新:这篇文章现在是我…

Sublime Text3配置Node.js开发环境
下载Nodejs插件,下载zip压缩包后解压链接: http://pan.baidu.com/s/1hsBk60k 密码: jrcv打开Sublime Text3,点击菜单“首选项(N)” >“浏览插件(B)”打开“Packages”文件夹,并将第1部的Node…

修改mysql的root密码
use msyql; update user set passwordpassword(新密码) where userroot; flush privileges; quitnet stop mysql #如果提示 发生系统错误5,就用管理员身份启动cmd.exe 转载于:https://www.cnblogs.com/walter371/p/4065904.html

iOS 开发之便捷宏定义
#define URL(A/*str*/) [NSURL URLWithString:A]// 图片 #define IMAGE(A/*str*/) [UIImage imageNamed:A]// 快速转换字符串 #define LD_STR(A/*str*/) [NSString stringWithFormat:"%ld",A] #define F2_STR(A/*str*/) [NSString stringWithFormat:"%.2f"…

rspec 测试页面元素_如何使用共享示例使您的RSpec测试干燥
rspec 测试页面元素by Parth Modi由Parth Modi 如何使用共享示例使您的RSpec测试干燥 (How to DRY out your RSpec Tests using Shared Examples) “Give me six hours to chop down a tree and I will spend the first four sharpening the axe.” — Abraham Lincoln“ 给我…

Windows搭建以太坊的私有链环境
Windows搭建以太坊的私有链环境 1、下载Geth.exe 运行文件,并安装https://github.com/ethereum/go-ethereum/releases/下载后,只有一个Geth.exe的文件2、cmd进入按章目录运行:geth -help看看是否可用geth命令3、在Geth安装目录下放置初始化创…

前50个斐波那契数
它有一个递推关系,f(1)1f(2)1f(n)f(n-1)f(n-2),其中n>23f(n)f(n2)f(n-2)-------------------------------------------- F(1) 1 F(2) 1 F(3) 2 F(4) 3 F(5) 5 F(6) 8 F(7) 13 F(8) 21 F(9) 34 F(10) 55 F(11) 89 F(12) 144 F(13) 233 F(14) 377 F(…

RAC -代替OC 中的代理
学以致用, 有的时候学习了很多理论 却还是忘了实践 OC 中代替代理 简洁编程 #import "ViewController.h" #import <ReactiveObjC.h> #import "SKView.h" interface ViewController ()endimplementation ViewController- (void)viewDidL…

深度学习 免费课程_深入学习深度学习,提供15项免费在线课程
深度学习 免费课程by David Venturi大卫文图里(David Venturi) 深入学习深度学习,提供15项免费在线课程 (Dive into Deep Learning with 15 free online courses) Every day brings new headlines for how deep learning is changing the world around us. A few e…

《音乐商店》第4集:自动生成StoreManager控制器
一、自动生成StoreManager控制器 二、查看 StoreManager 控制器的代码 现在,Store Manager 控制器中已经包含了一定数量的代码,我们从头到尾重新过一下。 1.访问数据库代码 首先,在控制器中包含了标准的 MVC 控制器的代码,为了使用…

StringUtils
/需要导入第三方jar包pinyin4j.jarimport net.sourceforge.pinyin4j.PinyinHelper;import java.util.regex.Matcher; import java.util.regex.Pattern;public class StringUtils {protected static final String TAG StringUtils.class.getSimpleName();/*** 增加空白*/public…

微信支付invalid total_fee 的报错
因为我的测试商品是0.01的 原因是微信支付的金额是不能带小数点的 直接在提交的时候 乘以 100操作 ,因为里面设置参数的时候是 以分为单位的 [packageParams setObject: price forKey:"total_fee"]; //订单金额,单位为分

帧编码 场编码_去年,我帮助举办了40场编码活动。 这是我学到的。
帧编码 场编码by Florin Nitu通过弗洛林尼图 去年,我帮助举办了40场编码活动。 这是我学到的。 (I helped host 40 coding events last year. Here’s what I learned.) Our local freeCodeCamp study group in Brasov, Romania just held its 40th event. We even…

HDU 4540 威威猫系列故事――打地鼠(DP)
D - 威威猫系列故事――打地鼠Time Limit:100MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Status Practice HDU 4540Description 威威猫最近不务正业,每天沉迷于游戏“打地鼠”。 每当朋友们劝他别太着迷游戏,应该好好工…

iOS 在每一个cell上添加一个定时器的方案
1 首先创建一个数组,用来创建所有的定时器的时间 - (NSMutableArray *)totalLastTime {if (!_totalLastTime) {_totalLastTime [NSMutableArray array];}return _totalLastTime; }2 当从网络请求过来时间之后,循环遍历,行数和时间作为Key&a…

用字符串生成二维码
需要导入Zxing.jar包import android.graphics.Bitmap;import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix;public class ZxingCode {/** * 用字符串生成…