Search code examples
flutterasynchronousproviderriverpoddio

How to access Riverpod provider value inside a class that doesnt know ref + Flutter


i am trying to finally understand state and reactiveness in a Flutter app (been developing in C# using MVVM for some years now)

Been messing with Riverpod these few days, watching several Youtube videos, i have a Provider for Dio client as this:

@riverpod
Dio dio(DioRef ref) {

var options = BaseOptions(
      baseUrl: myAwesomeEndpoint,
      headers: {
        HttpHeaders.contentTypeHeader: "application/json",
        HttpHeaders.acceptHeader: "application/json",
        HttpHeaders.authorizationHeader: "Basic fooBar",
      },);

  var dio = Dio(options);
  
  return dio;
}

Also, i have this Provider in a class to act as my Service Repo

@Riverpod(keepAlive: true)
class ApiService extends _$ApiService {
  static const basePath = "/whseactivity";

  @override
  ApiService build() {
    return ApiService();
  }

  Future<AllData> getAllData(DateTime date, String whseId) async {
    String endpoint = "$basePath/GetDoorsActions?Date=$date&WhID=$whseId";
    final response = // NEED TO GET THE DIO PROVIDER VALUE HERE
    final json = response.data! as Map<String, dynamic>;

    return AllData.fromJson(json);
  }
}

How to access the Dio Provider inside the getAllData() function in my ApiService if i dont have a ref?


Solution

  • Change your build to:

    late Dio dio;
    @override
    ApiService build() {
      dio = ref.watch(dioProvider);
      return ApiService();
    }
    

    and now you can use dio in the other methods.