【问题标题】:Flutter: StreamProvider catchError how toFlutter:StreamProvider catchError怎么办
【发布时间】:2019-11-18 10:34:09
【问题描述】:

我想知道是否有人可以告诉我如何实现 Flutter StreamProvider “catchError” 属性?

下面要添加的示例代码:

StreamProvider<LocationModelNormal>.value(
    initialData: LocationModelNormal.initialData(),
    stream: locationStreamInstance.specificLocation(_secondWonder),
    catchError: ?????????
),
class LocationModelNormal {
  final String name;
  LocationModelNormal({
    this.name
  });
  factory LocationModelNormal.fromMap(Map<String, dynamic> data) {
    return LocationModelNormal(
      name: data['name'] ?? '',

    );
  }
  factory LocationModelNormal.initialData() {
    return LocationModelNormal(
      name: '',
    );
  }
}

【问题讨论】:

    标签: flutter stream


    【解决方案1】:

    您需要使用密封类对数据进行建模:

    abstract class Data {}
    
    class Content implements Data {
      Content(this.data);
    
      final List<String> data;
    }
    
    class Error implements Data {
      Error(this.msg);
    
      final String msg;
    }
    
    class Loading implements Data {
      const Loading();
    }
    
    

    然后在提供程序中像这样使用:

    StreamProvider<Data>(
      builder: (_) async* {
        yield Content(['hello', 'world']);
      },
      initialData: const Loading(),
      catchError: (_, err) => Error(err.toString()),
      child: Container(),
    );
    

    这样消费:

    Consumer<Data>(
      builder: (_, data, __) {
        if (data is Loading) {
          return const CircularProgressIndicator();
        } else if (data is Error) {
          return Center(child: Text(data.msg));
        } else if (data is Content) {
          return ListView.builder(
            itemCount: data.data.length,
            itemBuilder: (_, index) => Text(data.data[index]),
          );
        }
        throw FallThroughError();
      },
    );
    

    【讨论】:

      【解决方案2】:

      你也可以这样做

      StreamProvider<DocumentSnapshot>.value(
              value: api.myDetails(mail),
              child: Builder(
                builder: (context){
                  var snapshot = Provider.of<DocumentSnapshot>(context);
                  if(snapshot == null){
                    return customF.loadingWidget();
                  }else{
                    return Stack(
                      children: <Widget>[
                        getMainListViewUI(),
                        getAppBarUI(),
                        SizedBox(
                          height: MediaQuery.of(context).padding.bottom,
                        )
                      ],
                    );
                  }
                }
              ),
            ),
      

      【讨论】:

        猜你喜欢
        • 2012-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        • 2015-06-30
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 2014-07-14
        相关资源
        最近更新 更多