'How to update ui based on error in resolving future in getx

Can we access the error generated during resolving future in GetxController in UI the same way we can do in future with snapshot.error

When using Future builder we can do snapshot.hasError and then we can update the UI based on the error like: image


Future<List<String> getNamesFromApi() async {
 // fetch from api
 // return result
}

...

FutureBuilder(
 future: getNamesFromApi(),
 builder: (context,snapshot) => 
  snapshot.hasError 
  ? Text("error reading data")
  : snapshot.hasData
    ? Text(snapshot.data[0])
    : SizedBox.shrink()

however in Getx when we resolve future inside the MyController and assign that to a variable in the controller like:

final List<String> name;
@override
onInit() async {
 name = await getNamesFromApi();
 update();
}

and then use that in ui like:

GetBuilder<MyController>(
 builder: (controller) => 
  controller.name != null 
  ? Text(controller.name[0]) 
  : SizedBox.shrink(),
)

here we have no way to know if the future resolved with an error. The value will just be null

Is there a way to do this in Getx without using a package for functional programming concepts such as either.



Solution 1:[1]

0

In order to verify if you are getting some data.. you can use the Either class in Dart which can imported from pub.dev. its make it easy to handle

for example,

final Either<String, List> result = await getProductList();

result.fold((exception) {
  //handle error here
}, (products) async {
  //get products here and you can do what you want
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julien Joseph Thomas