Network calls with Riverpod

Every app needs to make some network call to send and receive data from server side. And to make this simple for flutter app, we will use Riverpod to make our repository layer more simpler.

Don’t worry, I’ll show you how we can do this.

Riverpod comes with 2 version i.e. With code generation and Without code generation. Let’s explore both version and fetch our app user.

final userProvider = FutureProvider<User>((ref) {
  final result = await ref.read(httpClientProvider).get(currUserUri);
  final body = json.decode(result.body);
  return User.fromJson(body);
});
@riverpod
Future<User> user(UserRef ref) async {
  final result = await ref.read(httpClientProvider).get(currUserUri);
  final body = json.decode(result.body);
  return User.fromJson(body);
}

That’s it, you are ready to use it anywhere. So, why not let’s see how we can use it. First let’s use it inside a widget :-

class UserImage extends ConsumerWidget {
  const UserImage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return ref.watch(userProvider).when(
          data: (user) => Image.network(user.image),
          error: (e,s) => ImageErrorScreen(),
          loading: () => ImageLoader(),
        );
  }
}

Let suppose, In some notifier you want to wait for user to load first then update that notifier state. So, for that we can await on this provider future . Let’s see how :-

class UserCurrentBalanceNotifier extends AutoDisposeNotifier<int> {
  @override
  int build() => ref.read(sharedPref).get('localBalance');

  void sync() async {
    final user = await ref.read(userProvider.future);
    state = user.balance;
  }
}
@riverpod
class UserCurrentBalanceNotifier extends _$UserCurrentBalanceNotifier {
  @override
  int build() => ref.read(sharedPref).get('localBalance');

  void sync() async {
    final user = await ref.read(userProvider.future);
    state = user.balance;
  }
}

We can have so many application like this and using this pattern we can make our code easy to understand, test and debug. It also decouple UI from business logic.

Now let’s talk about pros and cons of using riverpod for network calls :-

Pros :-

  • Decouples UI from business logic
  • Easy to understand and use
  • Provides a consistent API for making network calls
  • Supports code generation

Cons :-

  • Riverpod needs to create and maintain a tree of providers, which can take up some memory
  • Riverpod is a relatively new library, so its documentation is not as well-developed as some other state management libraries.
  • Code generation for large and complex app can be slow.

Yes, we did it. Hope to see you in coming articles.