I want to display the value of MyLocationCountry in the appbar text, but the data is null. Meanwhile, when I make print($MyLocationCountry) the data is there. I want to try displaying country location data to my appbar and I am confused why the value data on Mylocationcountry does not appear in text form
This my code
`
Class _HomePageState extends State<HomePage> {
int currentIndexPage = 0;
final location = new Location();
String? locationError;
String? MylocationCountry, MylocationCity;
PrayerTimes? prayerTimes;
double? latitude, longitude, pLat, pLong;
@override
void initState() {
getLocationData().then((locationData) async {
if (!mounted) {
return;
}
if (locationData != null) {
setState(() {
prayerTimes = PrayerTimes(
Coordinates(locationData.latitude, locationData.longitude),
DateComponents.from(DateTime.now()),
CalculationMethod.karachi.getParameters());
pLat = prayerTimes!.coordinates.latitude;
pLong = prayerTimes!.coordinates.longitude;
print("Latitude : $pLat, Longitude : $pLong");
});
} else {
setState(() {
locationError = "Couldn't Get Your Location!";
});
}
List<MyLocation.Placemark> placemarks = await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
MylocationCountry = placemarks.reversed.last.country.toString();
MylocationCity = placemarks.reversed.last.locality.toString();
print("Country : $MylocationCountry, City : $MylocationCity");
});
//DateTime.now().hour >= 18 && DateTime.now().hour <= 19
super.initState();
}
@override
Widget build(BuildContext context) {
final country = this.MylocationCountry.toString();
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(225),
child: AppBar(
automaticallyImplyLeading: false,
title: RichText(
text: TextSpan(
text: country,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
children:
<TextSpan>[
TextSpan(
text: "\n$MylocationCity",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
),
),
]),),
`
The data is not show when i make the code like this, maybe someone can help me?
MyLocation.placemarkFromCoordinates
is asynchronous so it'll execute with some delay which means your build function runs before placemarks data is available. You need to update state after this call finishes.
setState((){
MylocationCountry = placemarks.reversed.last.country.toString();
MylocationCity = placemarks.reversed.last.locality.toString();
})