3 Errors handling of Flutter(Dart)

shogo.yamada
1 min readJan 21, 2019

--

catchError((e) => ~~~)

This is very popular error handling of Dart.

Example, This is the asynchronous function from Firestore.

Future<DocumentSnapshot> getUserInfo(String uid) {
return Firestore.instance.collection("user").document(uid).get(); }

Error handling is like this.

getUserInfo(uid).then((value) {
// success
}).catchError((err) {
// fails
})

try — catch

This error handling is try — catch pattern.

_setInitState() async {
try {
SharedPreferences preferences = await SharedPreferences.getInstance();
String uid = await preferences.get("uid");
User userInfo = await helper.getUserInfo(uid);
SharedPreferences prefs = await SharedPreferences.getInstance();
bool brightness = (prefs.getBool("isDark") ?? false);
if (this.mounted) {
setState(() {
_uid = uid;
_profileUrl = userInfo.iconUrl;
_brightness = brightness;
});
}
} catch (e) {
// エラーハンドリング
}

In this case, it is effective when handling errors with multi await.

Branch off builder

In this case, it is valid when FutureBuilder and StreamBuilder of Widget.

return FutureBuilder(
future: helper.getUsersGroupList(_uid),
builder: (context, snapshot) {

if (snapshot.hasError) {
// fail
}

// success
final List<DocumentSnapshot> groupIdList = snapshot.data.documents;

return ~~~~~ // functions when the asynchronous is success
});

Summary

1. catchError((e) => ~~~~)
2. try - catch
3. Branch off builder

In my app, I handling errors all of them in these three ways.

Since Dart is influenced by JavaScript specifications, it is basically similar to JavaScript error handling, is not it??

--

--

shogo.yamada
shogo.yamada

Written by shogo.yamada

普段はエンジニアやってます👨‍💻 自分の資産運用の記録として書いてり、プライベートなことを書いていきます。

No responses yet