Future Builder 无法与 Geolocator 配合使用
Future Builder not working with Geolocator with flutter
我对 flutter 有点陌生,我是第一次使用 Geolocator 插件。我正在尝试让 FutureBuilder 在构建时找到用户所在的城市,但它永远不会离开加载屏幕
这是我当前的代码:
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String currentTown;
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _getTown(),
builder: (context, snap) {
if(snap.connectionState == ConnectionState.waiting) {
return Loading();
} else {
return Center(
child: Text(
currentTown ?? null,
style: TextStyle(
color: Colors.white
),
),
);
}
}
);
}
Future _getTown() async {
print('get Town');
Position pos = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final coordinates = Coordinates(pos.latitude, pos.longitude);
var address = await Geocoder.local.findAddressesFromCoordinates(coordinates);
print(address.first.locality);
setState(() {
currentTown = address.first.locality;
});
}
}
pubspec.yaml:
dependencies:
geolocator: ^7.0.1
geocoder: ^0.2.1
我不确定我做错了什么。我尝试使用 future return String 值,但它仍然不会从加载屏幕改变。即使我使用 ConnectionState 它仍然不起作用
你需要return试试这个
Future _getTown() async {
return address.first.locality;
}
同时修改您的构建器
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data);
}
else{return loadingWidget();}
我对 flutter 有点陌生,我是第一次使用 Geolocator 插件。我正在尝试让 FutureBuilder 在构建时找到用户所在的城市,但它永远不会离开加载屏幕
这是我当前的代码:
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String currentTown;
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _getTown(),
builder: (context, snap) {
if(snap.connectionState == ConnectionState.waiting) {
return Loading();
} else {
return Center(
child: Text(
currentTown ?? null,
style: TextStyle(
color: Colors.white
),
),
);
}
}
);
}
Future _getTown() async {
print('get Town');
Position pos = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final coordinates = Coordinates(pos.latitude, pos.longitude);
var address = await Geocoder.local.findAddressesFromCoordinates(coordinates);
print(address.first.locality);
setState(() {
currentTown = address.first.locality;
});
}
}
pubspec.yaml:
dependencies:
geolocator: ^7.0.1
geocoder: ^0.2.1
我不确定我做错了什么。我尝试使用 future return String 值,但它仍然不会从加载屏幕改变。即使我使用 ConnectionState 它仍然不起作用
你需要return试试这个
Future _getTown() async {
return address.first.locality;
}
同时修改您的构建器
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data);
}
else{return loadingWidget();}