Shazamo Morebucks
Shazamo Morebucks

Reputation: 50

Flutter Riverpod/Provider: Setting an initial state for a stateNotifier

So I want to have a provider who's initial state will be the a user's location, this is what I have now, is this right?

import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/all.dart';
import 'package:location/location.dart';

class MapApiState {
  final LocationData userLocation;
  MapApiState({@required this.userLocation});
}

class MapNotifier extends StateNotifier<MapApiState> {
  static Location _location = Location();

  MapNotifier() : super(null) {
    _location.getLocation().then((initialState) =>
        super.state = MapApiState(userLocation: initialState));
  }
}

Is this the right approach? How do I now declare the global provider variable for this? The super(null) worries me. But I can't just put "super(_location.getLocation())"

Also, how should I then instantiate my global provider variable?

Upvotes: 1

Views: 4512

Answers (1)

EdwynZN
EdwynZN

Reputation: 5611

Well it almost depends of how you want to apply it in the lifecycle of your app, you can use StreamProvider or FutureProvider to get the location and then pass it to your StateNotifier

final locationProvider = FutureProvider<LocationData>((ref) {
  final Location _location = Location();

  return _location.getLocation();
});

final singleDetailDealProvider = StateNotifierProvider<MapNotifier>((ref) {
  final location = ref.watch(locationProvider);
  return MapNotifier(location.data?.value);
});

class MapNotifier extends StateNotifier<MapApiState> {
  MapNotifier(LocationData location) : super(location);
}

That way if you want to use the location somewhere else you can call locationProvider without depending on the state of MapNotifier

Upvotes: 2

Related Questions