如何利用FutureBuilder提高开发效率

2025-05-29 0 60

常见场景

  • 展示请求按钮
  • 用户点击按钮,显示loading
  • 展示数据或者错误

如何利用FutureBuilder提高开发效率

抽象模式

  1. 展示请求按钮(初始状态)
  2. 用户点击按钮,显示loading(请求中状态)
  3. 展示数据或者错误 (结束状态(成功或失败))

转换成程序语言

以上三种现实情况对应 asyncsnapshot 三个状态

  • connectionstate.none 初始态
  • connectionstate.waiting 请求态
  • connectionstate.done 完成态

    • snapshot.haserror 完成(异常)
    • snapshot.hasdata 完成(正常)

使用 futurebuilder 处理这个场景

这篇文章的主角,futurebuilder 就是为了解决这个问题存在的。它接收一个 future 请求,和对应以上几种情况的 widget 回调。即可把数据和界面串联起来,避免额外声明仅用来传递数据用的变量。

提前声明了一个 _showresult 变量,以表示页面是否触发请求。

并且封装了一个 _fetch() 网络请求。

?

1

2

3

4
future<map> _fetch() async {

return (await dio().get("https://jsonplaceholder.typicode.com/users/1"))

.data;

}

请求的结果是任意的,不管是封装好的对象,map,list,都可以,只要是一个 future<t>
把这个 future 调用安放到 futurebuilder 的 future 参数上, 并用 _showresult 来控制何时来触发这个请求。

?

1

2

3

4
futurebuilder(

future: _showresult ? _fetch() : null,

...

)

再把每一个 future 的结果对应的 widget 设置到 builder 参数上:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31
futurebuilder(

...

builder: (context, snapshot) {

switch (snapshot.connectionstate) {

case connectionstate.none: // -------- 初始态

return raisedbutton(

onpressed: () {

setstate(() {

_showresult = true; // 点击按钮,触发请求

});

},

child: text("start"),

);

case connectionstate.waiting: // -------- 请求态

return circularprogressindicator();

case connectionstate.done: // -------- 完成态

if (snapshot.haserror) { // 异常

return text(

'${snapshot.error}',

style: textstyle(color: colors.red),

);

} else { // 正常

return text(snapshot.data["name"]);

}

break;

default:

break;

}

return container();

},

),

总结

futurebuilder 把数据请求的 future<t> 中的数据 t 通过 builder 的 connectionstate 衍生出所有可能性,并在每个可能性里 return 一个 widgets。最终实现了 state -> ui 的目的

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 如何利用FutureBuilder提高开发效率 https://www.kuaiidc.com/89367.html

相关文章

发表评论
暂无评论