gpt4 book ai didi

Flutter:StreamProvider catchError 如何

转载 作者:行者123 更新时间:2023-12-03 13:30:46 30 4
gpt4 key购买 nike

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

最佳答案

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

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

关于Flutter:StreamProvider catchError 如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56942910/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com