Problems accessing state variables and the copyWith method in notifer using Riverpod In Flutter

69 views Asked by At

I'm facing a peculiar issue in this project wherein I cannot seem to access any state variable apart from isLoading from the state class nor use the copyWith method as it is not somehow recognized. I would like to know what I have done wrong despite this never being an issue ever. You will find the code for the state and the notifier below:

The State:

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

part 'homePageState.freezed.dart';

@freezed
class HomePageState with _$HomePageState {
  const factory HomePageState({
    @Default(true) bool isLoading,
    @Default(CameraPosition(target: LatLng(0, 0), zoom: 14)) CameraPosition cameraPosition,
    @Default([]) List<Marker> myMarker,
    @Default([
    Marker(
        markerId: MarkerId('First'),
        position: LatLng(22.644022415585223, 88.42673328033993),
        infoWindow: InfoWindow(title: 'Home')),
    Marker(
        markerId: MarkerId('Second'),
        position: LatLng(22.643450, 88.427420),
        infoWindow: InfoWindow(title: 'Home'))
  ]) List<Marker> markerList
  }) = _HomePageState;

  const HomePageState._();
}

And here's the notifier class:

class HomePageNotifier extends StateNotifier<HomePageState> {
  final Completer<GoogleMapController> controller = Completer();

  HomePageNotifier() : super(HomePageState());


  void addMarkers() {
    // myMarker.addAll(markerList);
    state = state.copyWith     //This is where I cannot seem to access neither the copyWith method, nor anything apart from the isLoading state    
  }
}

final homePageNotifier = StateNotifierProvider.autoDispose<HomePageNotifier, HomePageState>((ref) => HomePageNotifier());

Here's a snip of my pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: ^2.4.9
  google_maps_flutter: ^2.5.3
  geocoding: ^2.1.1
  geolocator: ^10.1.0
  json_annotation: ^4.8.1

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  freezed: ^2.4.6
  build_runner: ^2.4.8  
  json_serializable: ^6.7.1
  freezed_annotation: ^2.4.1
  json_annotation: ^4.8.1
1

There are 1 answers

4
Dhafin Rayhan On

I tried your code, build the required generated files and it's working perfectly. There's nothing wrong with the notifier, so most likely the problem is on the Freezed class.

  • Make sure you have run dart run build_runner build and see the outputs if there are any errors that need to be fixed.
  • Make sure the file name that includes the Freezed class is homePageState.dart.