I was wondering if someone could show me how to implement the Flutter StreamProvider "catchError" property?
Example code below to add to:
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: '',
);
}
}
You'll want to model your data using sealed classes:
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();
}
Then used like so in the provider:
StreamProvider<Data>(
builder: (_) async* {
yield Content(['hello', 'world']);
},
initialData: const Loading(),
catchError: (_, err) => Error(err.toString()),
child: Container(),
);
And consumed as such:
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();
},
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With