skip to Main Content

I am using Flutter with Riverpod and have a utility class MapServices that relies on Ref to access state providers. I’m trying to use this class within a ConsumerStatefulWidget, but I’m encountering a type cast error.

Detailed Description:

I have a utility class MapServices that looks like this:

class MapServices {
  final Ref ref;

  const MapServices({required this.ref});

  Future<List<AutoCompleteResult>> searchPlaces(String searchInput) async {
    final String url =
        'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$searchInput&key=${ref.read(googleMapsApiKey)}';

    var response = await http.get(Uri.parse(url));
    var json = convert.jsonDecode(response.body);
    debugPrint("AutoComplete JSON Results ==> ${json.toString()}");
    var results = json['predictions'] as List;
    return results.map((e) => AutoCompleteResult.fromJson(e)).toList();
  }

  Future<String?> getDistance({required String destination, required String origin}) async {
    try {
      final String url =
          'https://maps.googleapis.com/maps/api/distancematrix/json?destinations=$destination&origins=$origin&units=metric&key=${ref.read(googleMapsApiKey)}';
      final response = await http.get(Uri.parse(url));
      debugPrint(response.body);
      if (response.statusCode == 200) {
        return response.body;
      }
    } catch (e) {
      debugPrint(e.toString());
    }
    return null;
  }
}

In my UI, I have a ConsumerStatefulWidget where I try to use the MapServices class. Here’s how I’m attempting to call the getDistance method on a button tap:

class MyConsumerStatefulWidget extends ConsumerStatefulWidget {
  @override
  _MyConsumerStatefulWidgetState createState() => _MyConsumerStatefulWidgetState();
}

class _MyConsumerStatefulWidgetState extends ConsumerState<MyConsumerStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              String? distance = await MapServices(ref: ref as Ref).getDistance(
                origin:
                    '${ref.watch(originSelectedProvider).coordinates.latitude},${ref.watch(originSelectedProvider).coordinates.longitude}',
                destination:
                    '${ref.watch(destinationSelectedProvider).coordinates.latitude},${ref.watch(destinationSelectedProvider).coordinates.longitude}'
              );
              // Handle distance
            } catch (e) {
              debugPrint('Error: $e');
            }
          },
          child: Text('Get Distance'),
        ),
      ),
    );
  }
}

Problem:
I’m encountering the following error when I run the code and tap the button:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type ‘ConsumerStatefulElement’ is not a subtype of type ‘Ref<Object?>’ in type cast

What I Tried:

  • I used the ref parameter from the build method to instantiate MapServices.
  • I attempted to call the getDistance method and expected it to fetch the distance based on the origin and destination coordinates from my providers.
  • I looked through the Riverpod documentation and various online resources but couldn’t find a clear solution to this type cast issue.

Expected Outcome:

  • I expected to pass the ref object directly to MapServices and access the state required to make API calls without encountering type casting errors. My goal was to successfully call the getDistance method and get the result based on the state provided by Riverpod.

Actual Result:

  • Instead, I received a type casting error, indicating that the ConsumerStatefulElement (the type of ref object passed) could not be cast to Ref<Object?>.

Request:

  • Could you help me understand how to correctly pass the Ref from a ConsumerStatefulWidget to a class like MapServices in Riverpod? Is there a specific way to handle the Ref object within the ConsumerStatefulWidget context that I’m missing? Any guidance or code examples would be greatly appreciated.

Additional Context:

  • I’m using the Riverpod package for state management.
  • My goal is to access the state provided by Riverpod and use it to call APIs within MapServices.
  • Any insights into the proper usage of Ref within ConsumerStatefulWidget would be appreciated.
    Thank you for your help!

2

Answers


  1. Chosen as BEST ANSWER

    I was encountering a type cast error when using the Ref object from Riverpod in my MapServices utility class within a ConsumerStatefulWidget. The error message was:

    [ERROR /runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'ConsumerStatefulElement' is not a subtype of type 'Ref<Object?>' in type cast

    This occurred when I attempted to instantiate MapServices with the ref object from my ConsumerStatefulWidget's build method.

    Original Approach:

    Initially, my MapServices class required a Ref object to access the Google Maps API key:

    class MapServices {
      final Ref ref;
    
      const MapServices({required this.ref});
    
      Future<List<AutoCompleteResult>> searchPlaces(String searchInput) async {
        final String url =
            'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$searchInput&key=${ref.read(googleMapsApiKey)}';
    
        var response = await http.get(Uri.parse(url));
        var json = convert.jsonDecode(response.body);
        debugPrint("AutoComplete JSON Results ==> ${json.toString()}");
        var results = json['predictions'] as List;
        return results.map((e) => AutoCompleteResult.fromJson(e)).toList();
      }
    
      Future<String?> getDistance({required String destination, required String origin}) async {
        try {
          final String url =
              'https://maps.googleapis.com/maps/api/distancematrix/json?destinations=$destination&origins=$origin&units=metric&key=${ref.read(googleMapsApiKey)}';
          final response = await http.get(Uri.parse(url));
          debugPrint(response.body);
          if (response.statusCode == 200) {
            return response.body;
          }
        } catch (e) {
          debugPrint(e.toString());
        }
        return null;
      }
    }
    

    In my ConsumerStatefulWidget, I tried to use MapServices like this:

    class MyConsumerStatefulWidget extends ConsumerStatefulWidget {
      @override
      _MyConsumerStatefulWidgetState createState() => _MyConsumerStatefulWidgetState();
    }
    
    class _MyConsumerStatefulWidgetState extends ConsumerState<MyConsumerStatefulWidget> {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () async {
                try {
                  String? distance = await MapServices(ref: ref).getDistance(
                    origin:
                        '${ref.watch(originSelectedProvider).coordinates.latitude},${ref.watch(originSelectedProvider).coordinates.longitude}',
                    destination:
                        '${ref.watch(destinationSelectedProvider).coordinates.latitude},${ref.watch(destinationSelectedProvider).coordinates.longitude}'
                  );
                  // Handle distance
                } catch (e) {
                  debugPrint('Error: $e');
                }
              },
              child: Text('Get Distance'),
            ),
          ),
        );
      }
    }
    

    This resulted in the type cast error mentioned above.

    Solution: I modified the MapServices class to accept a String API key directly instead of the Ref object. This approach simplifies the class and resolves the type cast issue.

    Here’s the updated MapServices class:

    import 'package:haulfers_user_app/utils/essential_imports.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert' as convert;
    
    class MapServices {
      final String apiKey;
    
      const MapServices({required this.apiKey});
    
      Future<List<AutoCompleteResult>> searchPlaces(String searchInput) async {
        final String url =
            'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$searchInput&key=$apiKey';
    
        var response = await http.get(Uri.parse(url));
        var json = convert.jsonDecode(response.body);
        debugPrint("AutoComplete JSON Results ==> ${json.toString()}");
        var results = json['predictions'] as List;
        return results.map((e) => AutoCompleteResult.fromJson(e)).toList();
      }
    
      Future<String?> getDistance({required String destination, required String origin}) async {
        try {
          final String url =
              'https://maps.googleapis.com/maps/api/distancematrix/json?destinations=$destination&origins=$origin&units=metric&key=$apiKey';
          final response = await http.get(Uri.parse(url));
          debugPrint(response.body);
          if (response.statusCode == 200) {
            return response.body;
          }
        } catch (e) {
          debugPrint(e.toString());
        }
        return null;
      }
    }
    

    In the ConsumerStatefulWidget, I now use the WidgetRef to read the googleMapsApiKey and pass it directly to MapServices:

    class MyConsumerStatefulWidget extends ConsumerStatefulWidget {
      @override
      _MyConsumerStatefulWidgetState createState() => _MyConsumerStatefulWidgetState();
    }
    
    class _MyConsumerStatefulWidgetState extends ConsumerState<MyConsumerStatefulWidget> {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () async {
                try {
                  String? distance = await MapServices(apiKey: (ref.read(googleMapsApiKey) ?? "")).getDistance(
                    origin:
                        '${ref.watch(originSelectedProvider).coordinates.latitude},${ref.watch(originSelectedProvider).coordinates.longitude}',
                    destination:
                        '${ref.watch(destinationSelectedProvider).coordinates.latitude},${ref.watch(destinationSelectedProvider).coordinates.longitude}'
                  );
                  // Handle distance
                } catch (e) {
                  debugPrint('Error: $e');
                }
              },
              child: Text('Get Distance'),
            ),
          ),
        );
      }
    }
    

    Summary: By passing the API key directly to MapServices and accessing it through the WidgetRef in my widget, I was able to avoid the type cast error and successfully use the service. This method simplifies the process of passing dependencies into classes that interact with external services.


  2. It’s stated in the documentation that there is no shared interface between Ref and WidgetRef, so you can’t type cast one to the other.

    Instead of passing Ref object to the MapServices class, you should make each method its own provider. Riverpod is entity-based, so it makes more sense to make two separate providers that one exposes an AutoCompleteResult based on a search parameter, and the other exposes a String representing distance for a given destination and origin parameters. This can be done by using family providers. Both providers should depend on googleMapsApiKey provider.

    For the searchPlaces method, you could easily convert it to a family provider like this:

    final placesProvider = FutureProvider.autoDispose.family<AutoCompleteResult, String>((ref, searchInput) async {
      final String url =
          'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$searchInput&key=${ref.watch(googleMapsApiKey)}';
    
      var response = await http.get(Uri.parse(url));
      var json = convert.jsonDecode(response.body);
      debugPrint("AutoComplete JSON Results ==> ${json.toString()}");
      var results = json['predictions'] as List;
      return results.map((e) => AutoCompleteResult.fromJson(e)).toList();
    });
    

    For getDistance method, you could use a record for the family key:

    final distanceProvider = FutureProvider.autoDispose.family<String?, ({String destination, String origin})>((ref, route) async {
      final String url =
          'https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${route.destination}&origins=${route.origin}&units=metric&key=$apiKey';
      final response = await http.get(Uri.parse(url));
      debugPrint(response.body);
      if (response.statusCode == 200) {
        return response.body;
      }
    });
    

    If you use code generation, that would be even more straightforward and easier:

    @riverpod
    Future<AutoCompleteResult> places(PlacesRef ref, String searchInput) async {
      // ...
    }
    
    @riverpod
    Future<String?> distance(DistanceRef ref, {required String destination, required String origin}) async {
      // ...
    }
    

    Additional notes:

    In a provider’s body (such as the function body of placesProvider), you should only use ref.watch. In a callback (such as onPressed callback), you should only use ref.read.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search