Type cast error when using Ref in a class as a parameter with ConsumerStatefulWidget in Flutter Riverpod

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, 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'),
        ),
      ),
    );
  }
}

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!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật