我的代码没有错误地获取用户位置。当用户拒绝对该位置的访问并且稍后他想允许它时,就会出现问题。 我不知道如何处理这个过程。
这些是步骤:
initState 询问位置 -> 如果用户允许访问一切正常。
initState -> 用户拒绝访问。 如果用户拒绝访问,我将无法再次请求访问,因此我将永远不会获得用户的职位。 我需要了解如何处理拒绝阶段。 这是代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';
class Maps extends StatefulWidget {
static Future<void> show(
BuildContext context,
) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Maps(),
fullscreenDialog: true,
),
);
}
@override
_MapsState createState() => _MapsState();
}
Future<Position> locateUser() async {
return Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
}
class _MapsState extends State<Maps> {
Geolocator geolocator = Geolocator();
String _location;
String _addressLine;
bool done = false;
@override
void initState() {
_getCurrentLocation();
super.initState();
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: _navBar(),
child: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.4,
width: MediaQuery.of(context).size.width * 0.6,
child: Center(
child: Column(
children: [
done == false
? textOnScreen("Need to get the position")
: textOnScreen("val 1: $_location, val 2: $_addressLine"),
FlatButton(
child: Text("Get location"),
onPressed: () {
setState(() {
done = false;
_getCurrentLocation();
});
},
),
],
),
),
),
),
);
}
Widget textOnScreen(String text) {
return FlatButton(
onPressed: null,
child: Text(text),
);
}
Widget _navBar() {
return CupertinoNavigationBar(
backgroundColor: Colors.blue,
middle: Text(
'Get position',
style: TextStyle(
color: Colors.white,
),
),
);
}
Future<void> _getLocation(Position position) async {
debugPrint('location: ${position.latitude}');
final coordinates = new Coordinates(position.latitude, position.longitude);
List<Address> addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
Address first = addresses.first;
_location = "${first.featureName}";
_addressLine = " ${first.addressLine}";
setState(() {
done = true;
});
}
void _getCurrentLocation() {
// if (await )
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
_getLocation(position);
}).catchError((e) {
print(e);
});
}
}