0

我有一个用于加载视频帖子列表的流生成器​​。每当发生错误时,我都会向接收器添加一个错误,并且StreamBuilder会显示一条带有“重试”按钮的错误消息。我的问题是,当我按下按钮时,什么都没有发生(视觉上),但我想在重试时用 spinLoader 替换错误消息

我将如何实现这一目标?

我正在考虑向接收器添加一个布尔值并检查 snapshot.data 是否为布尔值,如果是则返回 spinLoader,但这似乎违反直觉。

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        color: backgroundColor,
        child: StreamBuilder(
          stream: _streamController.stream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return buildRelatedList(snapshot.data);
            } else if (snapshot.hasError) {
              return retryButton();
            } else {
              return _spinningLoader;
            }
          },
        ),
      ),
    );
  }

  _fetchVideos() async {
    List videos = await RelatedVideos.fetchVideos(
        id: widget.id);
    if (videos.isEmpty) {
      _streamController.sink.addError('error loading');
    } else {
      _streamController.sink.add(videos);
    }
  }
4

1 回答 1

0

您可以使用ConnectionState

  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if (snapshot.hasError)
      return Text('Error: ${snapshot.error}');
    switch (snapshot.connectionState) {
      case ConnectionState.none: return Text('Select lot');
      case ConnectionState.waiting: return Text('Awaiting bids...');
      case ConnectionState.active: return Text('\$${snapshot.data}');
      case ConnectionState.done: return Text('\$${snapshot.data} (closed)');
    }
    return null; // unreachable
  },
)

这会将连接状态返回到异步计算。您也可以将Text小部件更改为另一个小部件,例如您可以使用 CircularProgressIndicator();

https://api.flutter.dev/flutter/widgets/ConnectionState-class.html

https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html

https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html

于 2020-01-24T10:24:05.580 回答