首页 > 解决方案 > 如何在 Flutter 的文本中使用异步函数的结果?

问题描述

这周我开始学习 Flutter。我正在尝试使用 Geolocator 包获取设备的位置,但我不习惯异步功能。我想在 AppBar 标题的文本中使用 position.latitude。我在代码中写了<位置信息到这里>以显示正确的位置。下面是我的代码。

class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: buildAppBar(context),
);
}

AppBar buildAppBar(context) {
var position = null;

getCurrentPosition().then((position) => {position = position});

return AppBar(
    centerTitle: true,
    backgroundColor: kPrimaryColor,
    elevation: 0,
    toolbarHeight: MediaQuery.of(context).size.height * 0.07,
    title: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          icon: const Icon(Icons.place),
          iconSize: 15,
          onPressed: () {},
        ),
        const Text(<position information goes here>,
            style: TextStyle(fontSize: 12)),
      ],
    ));
}

Future<Position> getCurrentPosition() async {
 Position position = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high);

  return position;
  }
}

标签: flutterdartasync-await

解决方案


  1. 您的页面必须是有状态的才能更改它的状态。无状态小部件是静态的,您可以在小部件不变且用户不与屏幕交互时使用它们。
  2. 您必须调用 setState() 方法,以便您的页面知道发生了一些变化。
  3. 稍后,如果您希望改进您​​的代码,请使用状态管理(MobX、GetX、Cubit、RxDart)而不是 setStates。使用 setState 时,widget-tree 下的所有小部件都会重新加载,因此会消耗更多的 CPU 和 GPU。

尝试这样的事情:

import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  var position = null;

  @override
  void initState() {
    getCurrentPosition().then((position) {
      setState(() {
        position = position;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
    );
  }

  AppBar buildAppBar(context) {
    return AppBar(
        centerTitle: true,
        backgroundColor: kPrimaryColor,
        elevation: 0,
        toolbarHeight: MediaQuery.of(context).size.height * 0.07,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              icon: const Icon(Icons.place),
              iconSize: 15,
              onPressed: () {},
            ),
            const Text(position ?? '', style: TextStyle(fontSize: 12)),
          ],
        ));
  }

  Future<Position> getCurrentPosition() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    return position;
  }
}

如果您有问题,请给我反馈。


推荐阅读