flutter - 如何在 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;
}
}
解决方案
- 您的页面必须是有状态的才能更改它的状态。无状态小部件是静态的,您可以在小部件不变且用户不与屏幕交互时使用它们。
- 您必须调用 setState() 方法,以便您的页面知道发生了一些变化。
- 稍后,如果您希望改进您的代码,请使用状态管理(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;
}
}
如果您有问题,请给我反馈。
推荐阅读
- python - Statsmodel ADF 函数返回“TypeError:‘函数’对象不可下标”
- text - JMeter - 根据响应中的文本在图中有单独的线的方法
- r - 归纳树规则的覆盖范围和准确性
- codeceptjs - 如何在测试用例期间设置输入类型 datetime-local
- r - 每个 group_by 添加 n(空)行
- c# - VS C# 简单的单选按钮开关
- node.js - 安装我的私有 github 存储库时,monorepo 路径错误
- azure-devops - YAML 管道中路径过滤器中通配符的可用性
- php - Wordpress 按元值日期排序
- angular - 如何在图像上渲染 D3 js 的面积图?(在 Angular 8 中)