Can’t update a riverpod notifier when I inject a service

Introduction

I’m working with riverpod for state management in my application.

I simply want to update a variable when I call my notifier.

The problem occurs when I inject my service into this notifier.


Code

Here is my simplified page, I have a button which updates the orientation of my map through a mapOrientationNotifier.
I also display the compass orientation in real time through a mapCompassNotifier.

map_page.dart:

class MapPage extends ConsumerWidget {
  const MapPage({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final mapCompassNotifier = ref.watch(mapCompassNotifierProvider);
    final mapOrientationNotifier = ref.watch(mapOrientationNotifierProvider);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: mapCompassNotifier.compass != null
          ? Text('Direction: ${mapCompassNotifier.compass!.degree!.toStringAsFixed(2)}°')
          : const Text('Direction: 0°'),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            onPressed: (){ 
              print("Button pressed. Current mapOrientationState: ${mapOrientationNotifier.mapOrientationState}"); // Debug print
              mapOrientationNotifier.updateMapOrientationState();
             },
            child: mapOrientationNotifier.mapOrientationState == MapOrientationState.north
              ? const Icon(Icons.navigation)
              : const Icon(Icons.assistant_navigation),
          ),       
        ],
      ),
      body: FlutterMap(
        ... some code
      ),
    );
  }
}

Well now let’s update the mapOrientationState variable through the updateMapOrientationState method in my mapOrientationNotifier.

map_orientation_notifier.dart:

final mapOrientationNotifierProvider = ChangeNotifierProvider((ref) {
  return MapOrientationNotifierProvider(
    mapController: ref.watch(mapControllerProvider),
  );
});

class MapOrientationNotifierProvider extends ChangeNotifier {
  final MapController mapController;

  MapOrientationState mapOrientationState = MapOrientationState.north;
  bool _isDisposed = false;

  MapOrientationNotifierProvider({
    required this.mapController,
  });

  void updateMapOrientationState() {
    if (_isDisposed) return;

    if (mapOrientationState == MapOrientationState.north) {
      mapOrientationState = MapOrientationState.heading;
    } else if (mapOrientationState == MapOrientationState.heading) {
      mapOrientationState = MapOrientationState.north;
      mapController.rotate(0);
    }
    notifyListeners();
  }

  @override
  void dispose() {
    _isDisposed = true;
    super.dispose();
  }
}

It works no problem.
Now I would like to inject a compass Service which I use to retrieve the orientation of the compass in real time.
My compassService works since I can display the value in the appBar in map_page.dart through the compassNotifier.

compass_service.dart:

final compassServiceProvider = ChangeNotifierProvider<CompassService>((ref) {
  return CompassService(
    getCompassUseCase: ref.watch(getCompassUseCaseProvider),
  );
});

class CompassService with ChangeNotifier {
  final GetCompassUseCase getCompassUseCase;

  CompassService({
    required this.getCompassUseCase,
  }){
    _subscribeToCompass();
  }

  StreamSubscription<ResultEntity<CompassEntity?, AppException>>? _compassSubscription;
  CompassEntity? _compass;
  CompassEntity? get compass => _compass;

  void _subscribeToCompass() {
    _compassSubscription = getCompassUseCase.execute().listen(
      (result) {
        result.toResult(
          success: (compass) {
            _compass = compass;
            notifyListeners();
          },
          failure: (_) {
            _compass = null;
            notifyListeners();
          },
        );
      },
      onError: (error) {
        _compass = null;
        notifyListeners();
      }
    );
  }
  
  @override
  void dispose() {
     _compassSubscription?.cancel();
    super.dispose();
  }
}

map_compass_notifier.dart:

final mapCompassNotifierProvider = ChangeNotifierProvider((ref) { 
  return MapCompassNotifierProvider(
    compassService: ref.watch(compassServiceProvider),
  );
});

class MapCompassNotifierProvider extends ChangeNotifier{
  final CompassService  compassService;

  MapCompassNotifierProvider({
    required this.compassService,
  }){
    _initialize();
  }

  CompassEntity? get compass => compassService.compass;

  LocationMarkerHeading? get userHeading => compassService.compass != null 
    ? UserMarkerHelper.convertToLocationMarkerHeading(compass: compassService.compass!)
    : null;

  void _initialize() {
    compassService.addListener(_updateCompass);
  }

  void _updateCompass() {
    notifyListeners();
  }

  @override
  void dispose() {
    compassService.removeListener(_updateCompass);
    super.dispose();
  }
}

Code with service not works

Now that all this is in place I want to be able to inject my compass service into the mapOrientationNotifier so that I can use the compass value to rotate my map when I change the orientation with mapOrientationState.

Let’s take my mapOrientationNotifier and inject the service:

map_orientation_notifier.dart:

final mapOrientationNotifierProvider = ChangeNotifierProvider((ref) {
  return MapOrientationNotifierProvider(
    mapController: ref.watch(mapControllerProvider),
    compassService: ref.watch(compassServiceProvider), // => Add this line
  );
});

class MapOrientationNotifierProvider extends ChangeNotifier {
  final MapController mapController;
  final CompassService compassService; // => Add this line

  MapOrientationState mapOrientationState = MapOrientationState.north;
  bool _isDisposed = false;

  MapOrientationNotifierProvider({
    required this.mapController,
    required this.compassService, // => Add this line
  }) {
    compassService.addListener(_onCompassChanged); // => Add this line
  }

  // => Add this method
  void _onCompassChanged() {
    if (_isDisposed) return;

    if (mapOrientationState == MapOrientationState.heading) {
      if (compassService.compass?.degree != null) {
        //mapController.rotate(compassService.compass!.degree!);
      }
    }
    notifyListeners();
  }

  void updateMapOrientationState() {
    if (_isDisposed) return;

    if (mapOrientationState == MapOrientationState.north) {
      mapOrientationState = MapOrientationState.heading;
    } else if (mapOrientationState == MapOrientationState.heading) {
      mapOrientationState = MapOrientationState.north;
      //mapController.rotate(0);
    }
    notifyListeners();
  }

  @override
  void dispose() {
    _isDisposed = true;
    compassService.removeListener(_onCompassChanged); // => Add this line
    super.dispose();
  }
}

Problem

So I just injected the service but the mapOrientationState variable is no longer updated, I don’t understand…

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