Flutter:StreamProvider catchError如何

时间:2019-07-08 21:44:07

标签: flutter stream

我想知道是否有人可以向我展示如何实现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: '',
    );
  }
}

2 个答案:

答案 0 :(得分:0)

您将要使用密封类对数据建模:

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();
  },
);

答案 1 :(得分:0)

您也可以这样做

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,
                  )
                ],
              );
            }
          }
        ),
      ),