Skip to content

Instantly share code, notes, and snippets.

@devmike01
Last active October 31, 2020 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devmike01/007b64e57b442da17d31797bd899894c to your computer and use it in GitHub Desktop.
Save devmike01/007b64e57b442da17d31797bd899894c to your computer and use it in GitHub Desktop.
Some code snippet to handle your messy API call states. ;) #EndSARS
class ApiState<T> {
String message;
T data;
ApiStates state;
ApiState(this.state, this.data, this.message);
static ApiState<T> loading<T>() {
return ApiState<T>(ApiStates.Loading, null, null);
}
static ApiState<T> success<T>(T data) {
return ApiState<T>(ApiStates.Success, data, null);
}
static ApiState<T> error<T>(String error) {
return ApiState<T>(ApiStates.Failed, null, error);
}
}
enum ApiStates { Loading, Success, Failed }
// Usage in Model/Bloc class
final _intStreamController = StreamController<ApiState<int>>();
final get intStream => _intStreamController.stream;
_intStreamController.sink.add(ApiStatus.success(200)); // This is called when the API call is successful
_intStreamController.sink.add(ApiStatus.error("Some crazy error message")); //Called when an error occurs in the API
_intStreamController.sink.add(ApiStatus.loading()); //Data is currently loading
//Usage in your UI
YourBloc _yourBloc = new YourBloc();
//This should be added to the base class of your UI
extension<T> on AsyncSnapshot<ApiState<T>> {
bool get isSuccess =>
this.data != null && this.data.state == ApiStates.Success;
bool get isLoading =>
this.data != null && this.data.state == ApiStates.Loading;
bool get hasFailed =>
this.data != null && this.data.state == ApiStates.Failed;
//This should be call only if `hasFailed` is true
String get errorMessage => this.data.message;
T get value => this.data.data;
}
//Now you can check the state in your stream builder.
new StreamBuilder<ApiState<int>>(
stream: _yourBloc.intStream
builder: (context, snapshot) {
return snapshot.isLoading
? Text("Its loading")
: snapshot.hasFailed
? Text(snapshot.errorMessage ??
"It has failed like the Nigerian govt.")
: Text("It's successful ${snapshot.value}");
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment