flutterriverpoddio

How do I manage Dio in Flutter projects using Riverpod


Let's say we have API and we want to manage all api with Dio. How can I create base Dio options?

I want to under control api response errors, connection timeouts etc. What is the best way to connecting API with Dio using Riverpod?


Solution

  • I think you could start from the easiest way to use riverpod :

    final dioProvider = Provider<Dio>((ref) => Dio());
    

    In this manner you define a provider used globally that does not create a new Dio() object every time. Then, you can add some stuff like this:

       class MyDioUseCase {
         final Dio dio;
         MyDioUseCase(this.dio);
    
         void request() async {
           Response response;
          response = await dio.get('/test?id=12&name=dio');
          print(response.data.toString());
          // The below request is the same as above.
          response = await dio.get(
            '/test',
            queryParameters: {'id': 12, 'name': 'dio'},
          );
          print(response.data.toString());
        }
    }
    
    @Riverpod(keepAlive: true)
    Dio dioProvider(DioProviderRef ref) => Dio();
    
    @Riverpod(keepAlive: true)
    Dio myDioUseCase(MyDioUseCaseRef ref) => MyDioUseCase (ref.watch(dioProvider));