【发布时间】:2020-05-23 18:57:26
【问题描述】:
这是我的第一个扁平化应用。我尝试做的是这样的 ab 容器布局:
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("LocInfo"),
),
body:
ListView(
children: [
//_getCurrentLocation(),
locSection,
addressSection,
timeSection,
],
),
);
}
在布局里面我有这个小部件:
Widget locSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
/*1*/
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
/*2*/
Container(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
'Location (LAT/LNG)',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
if (_currentPosition != null)
Text(
"LAT: ${_currentPosition.latitude}, LNG: ${_currentPosition.longitude}",
style: TextStyle(
color: Colors.grey[500],
),
),
],
),
),
/*3*/
Icon(
Icons.near_me,
),
],
),
);
我还有一个获取坐标的功能:
_getCurrentLocation() {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
问题是,我收到了这个错误:
lib/home_page.dart:52:21:错误:无法在字段中访问“this” 初始化程序读取'_currentPosition'。 if (_currentPosition != null)
那么我如何在这个位置访问_currentPosition?
【问题讨论】: