I am new to flutter and need some help please I have this screen with GoogleMaps (simplified for here):
class OrderDetailsScreen1 extends StatefulWidget {
const OrderDetailsScreen1({
Key? key,
}) : super(key: key);
@override
_OrderDetailsScreen1State createState() => _OrderDetailsScreen1State();
}
class _OrderDetailsScreen1State extends State<OrderDetailsScreen1> {
@override
Widget build(BuildContext context) {
final googleMapsNotifier =
Provider.of<GoogleMapsNotifier>(context, listen: true);
double latitude = -33.75;
double longitude = -70.67;
if (googleMapsNotifier.currentLocation != null) {
latitude = googleMapsNotifier.currentLocation!.latitude;
longitude = googleMapsNotifier.currentLocation!.longitude;
}
return Scaffold(
body: SafeArea(
child: SizedBox(
height: 300,
child: GoogleMap(
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(latitude, longitude),
zoom: 14,
),
),
),
),
);
}
}
I push this screen from the previous one like this
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Provider<GoogleMapsNotifier>(
create: (_) => GoogleMapsNotifier(),
child: OrderDetailsScreen1(
),
)));
},
And I have a class GoogleMapsNotifier with ChangeNotifier
like this
class GoogleMapsNotifier with ChangeNotifier {
final geolocatorService = GeolocatorService();
Position? currentLocation;
GoogleMapsNotifier() {
setCurrentLocation();
}
setCurrentLocation() async {
currentLocation = await geolocatorService.determinePosition();
print(currentLocation!.latitude);
notifyListeners();
}
}
Inside setCurrentLocation()
of GoogleMapsNotifier
it get currentLocation
fine and prints it fine. But notifyListeners()
does not pass data back to the UI (OrderDetailsScreen1). It does not react and I have no errors in the Console. Where is the mistake?
UPD: I tried to change the MaterialPageRoute to the below and it didn't help
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Provider.value(
value: Provider.of<GoogleMapsNotifier>(context),
child: OrderDetailsScreen1(),
)));
},
CodePudding user response:
You should pass the existing provider
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Provider.value(
value: googleMapsNotifier,
child: OrderDetailsScreen1(
),
)));
},
CodePudding user response:
You need to wrap your Ui widget with Consumer of specific provider. So it will be update state of your Ui through provider.