skip to Main Content

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?

3

Answers


  1. If you look at the code carefully, you will see that you are not calling setState after setting the value of MylocationCountry.

    Here is an updated code snippet:

    setState(() {
              List<MyLocation.Placemark> placemarks =
                  await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
              MylocationCountry = placemarks.reversed.last.country.toString();
              MylocationCity = placemarks.reversed.last.locality.toString();
            });
    
    Login or Signup to reply.
  2. I suggest you a futureBuilder approach that could be helpful:

    class _HomePageState extends State<HomePage> {
      ...
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(225),
            child: FutureBuilder(
              future: MyLocation.placemarkFromCoordinates(pLat!, pLong!),
              builder: (BuildContext context, AsyncSnapshot<List<MyLocation.Placemark>> snapshot) {
                if (snapshot.hasData) {
                  MylocationCountry = snapshot.data!.reversed.last.country.toString();
                  MylocationCity = snapshot.data!.reversed.last.locality.toString();
                }
                return AppBar(
                  automaticallyImplyLeading: false,
                  title: RichText(
                    text: TextSpan(
                      text: MylocationCountry ?? '',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w500,
                      ),
                      children: <TextSpan>[
                        TextSpan(
                          text: "n${MylocationCity ?? ''}",
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          ...
        );
      }
    }
    
    
    
    
     
    
    Login or Signup to reply.
  3. 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();
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search