Flutter-异步
本文最后更新于 587 天前

1. FutureBuilder

Center(
    child: FutureBuilder(
      // initialData: "加载中",
      // future: Future.delayed(Duration(seconds: 2), () => "123"),
      future: Future.delayed(Duration(seconds: 2), () => throw "网络错误error"),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot){
        // snapshot.connectionState
        if(snapshot.hasError) {
          return Text("{snapshot.error}");
        }
        // initialData
        if(snapshot.hasData) {
          return Text("数据{snapshot.data}");
        }
        return CircularProgressIndicator();
      },
    ),
  ),
);

2. StreamBuild(StreamController)

默认: 单次监听 (无监听时 会缓存事件)
多监听: StreamController.broadcast(); (无监听时 不会缓存事件)

其他Stream构建方式

Stream<DateTime> getDate() async*{
    while(true) {
        await Future.delayed(Duration(seconds: 1));
        yield DateTime.now();
    }
}
StreamController _streamController = StreamController();
// StreamController _streamController = StreamController.broadcast();
int index = 0;

@override
Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: Center(
        child: StreamBuilder(
          stream: _streamController.stream,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot){
            // snapshot.connectionState
            if(snapshot.hasError) {
              return Text("{snapshot.error}");
            }
            // initialData
            if(snapshot.hasData) {
              return Text("数据{snapshot.data}");
            }
            return CircularProgressIndicator();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _streamController.sink.add("event ${index++}");
        },
      ),
    );
}
iichen:https://iichen.cn/?p=564
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇