MylocationCountry值如何出现在Text()应用栏中?

huangapple go评论69阅读模式
英文:

How can MylocationCountry values appear in the Text() appbar?

问题

我想在应用栏文本中显示MyLocationCountry的值,但数据为空。同时,当我使用print($MyLocationCountry)时,数据是存在的。我想尝试在我的应用栏中显示国家位置数据,但我困惑为什么Mylocationcountry的值不以文本形式显示。

我的代码中的问题是:数据不显示,也许有人可以帮助我?
英文:

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?

答案1

得分: 0

如果你仔细查看代码,你会发现在设置了MylocationCountry的值之后,你没有调用setState

以下是更新后的代码片段:

setState(() {
    List<MyLocation.Placemark> placemarks =
        await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
    MylocationCountry = placemarks.reversed.last.country.toString();
    MylocationCity = placemarks.reversed.last.locality.toString();
});
英文:

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&lt;MyLocation.Placemark&gt; placemarks =
              await MyLocation.placemarkFromCoordinates(pLat!, pLong!);
          MylocationCountry = placemarks.reversed.last.country.toString();
          MylocationCity = placemarks.reversed.last.locality.toString();
        });

答案2

得分: 0

我建议您使用FutureBuilder的方法,可能会有所帮助:

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,
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
      ...
    );
  }
}
英文:

I suggest you a futureBuilder approach that could be helpful:

class _HomePageState extends State&lt;HomePage&gt; {
  ...

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(225),
        child: FutureBuilder(
          future: MyLocation.placemarkFromCoordinates(pLat!, pLong!),
          builder: (BuildContext context, AsyncSnapshot&lt;List&lt;MyLocation.Placemark&gt;&gt; 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 ?? &#39;&#39;,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                  children: &lt;TextSpan&gt;[
                    TextSpan(
                      text: &quot;\n${MylocationCity ?? &#39;&#39;}&quot;,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
      ...
    );
  }
}

答案3

得分: 0

MyLocation.placemarkFromCoordinates 是异步的,因此它会有一些延迟,这意味着在地标数据可用之前,您的构建函数会运行。您需要在此调用完成后更新状态。

setState(() {
  MylocationCountry = placemarks.reversed.last.country.toString();
  MylocationCity = placemarks.reversed.last.locality.toString();
})
英文:

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();
})

huangapple
  • 本文由 发表于 2023年5月10日 11:40:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76214736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定