I'm using FutureProvider.value in provider package and trying to get location data with Provider.of<T>(context) from this provider, but I can only get null. Instead of that, I can get the data when I use FutureBuilder, so I think my code around provider is wrong. I hope you will help me.
class _HomePageState extends State<HomePage> {
final LocationService _locationService = LocationService();
Future<LocationModel?> getUserLocation() async {
final locationData = await _locationService.getLocation();
if (locationData != null) {
final placeMark =
await _locationService.getPlaceMark(locationData: locationData);
if (placeMark == null) {
return null;
}
return LocationModel(
country: placeMark.country ?? '',
adminArea: placeMark.administrativeArea ?? '',
subAdminArea: placeMark.subAdministrativeArea ?? '',
city: placeMark.locality ?? '',
subCity: placeMark.subLocality ?? '',
street: placeMark.street ?? '',
);
}
return null;
}
@override
Widget build(BuildContext context) {
return FutureProvider<LocationModel?>.value(
value: getUserLocation(),
initialData: null,
child: Scaffold(
appBar: AppBar(
title: const Text('Welcome!'),
actions: [
IconButton(
icon: const Icon(Icons.person),
onPressed: () {
Navigator.pushNamed(context, '/profile');
},
),
],
backgroundColor: const Color.fromARGB(255, 205, 106, 99)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('--I want to display location here--'),
Text(Provider.of<LocationModel?>(context)?.city! ??
Provider.of<LocationModel?>(context).toString()),
FutureBuilder(
future: getUserLocation(),
builder: (BuildContext context,
AsyncSnapshot<LocationModel?> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.city!);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
......