Best Practices: Handling loading/error mutation states #1231
Replies: 5 comments 11 replies
-
Riverpod currently is unopinionated on the matter. The reasoning is that there's not really an ideal solution with the current state of Dart. For Riverpod to do something about this use case, it'll have to wait until metaprogramming is released. At which point, Riverpod will have built-in support for this My current plan for Riverpod+metaprogramming is to support: @provider
class _$TodoListController {
Future<List<Todo>> create() async {
// can use ref.watch here if desired
return <some HTTP request>
}
@mutation
Future<void> add(Todo todo) async {
await http.post('api/todos/add', todo.toJson();
// <somehow update the list of todos>
}
}
// in some widget:
Widget build(context, ref) {
AsyncValue<List<Todo>> todos = ref.watch(TodoListController);
// as usual
Mutation add = ref.watch(TodoListController.add);
// for mutations like you defined, which allows:
return Column(
children: [
if (add.hasError) Text('failed to add todo ${add.error}'),
ElevatedButton(
onTap: () => add(Todo('new todo')),
child: Text('submit'),
),
],
);
} |
Beta Was this translation helpful? Give feedback.
-
I've been thinking about my approach and the generic version by @chimon2000. In essence, I always do this in the use case above:
It seems acceptable to repeat this for new widgets, though I was wondering if this is something that can be simplified further with Flutter Hooks? (I'll admit I haven't used them extensively so I need to get a better feel for what use cases they solve effectively) |
Beta Was this translation helpful? Give feedback.
-
What I usually did was to create a provider and set it up as a snackbar to show any error. in some view_model:
inside a widget
|
Beta Was this translation helpful? Give feedback.
-
another possible way I saw on @vandadnp 's course is to make a consumer in the root of you widgets that listens to a loading provider
and IsLoadingProvider is combined of listening for loading of multiple providers of type
It's working fine but I was thinking about another states such as |
Beta Was this translation helpful? Give feedback.
-
Consider checking out my https://pub.dev/packages/riverpod_mutations_generator It tries to fit remi's own preferred api for when macros come out, and as far as i can tell, seems to work well enough. |
Beta Was this translation helpful? Give feedback.
-
Recently read @bizz84's article on handling loading/error states when executing asynchronous actions. In it, he describes creating controllers per action that update their AsyncValue as they perform an action. For example:
I also put together a very simple generic version of this:
ActionController
be improved or simplified?Thanks in advance for the feedback!
Beta Was this translation helpful? Give feedback.
All reactions