使用库:location
在pubspec.yaml中导入:
dependencies:
#地理位置
location: ^2.3.5
示例代码:
void main() => runApp(WSLocation());
import 'package:flutter/material.dart';
//地理位置
import 'package:location/location.dart';
class WSLocation extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LocationPage(title: 'Flutter Demo Home Page'),
);
}
}
class LocationPage extends StatefulWidget {
LocationPage({Key key, this.title}) : super(key: key);
final String title;
@override
LocationPageState createState() => LocationPageState();
}
class LocationPageState extends State<LocationPage> {
int _counter = 0;
LocationData currentLocation;
var location = new Location();
@override
void initState() {
super.initState();
}
_incrementCounter() async {
try {
currentLocation = await location.getLocation();
} catch (e) {
if (e.code == 'PERMISSION_DENIED') {
print('Permission denied');
}
currentLocation = null;
}
location.onLocationChanged().listen((LocationData currentLocation) {
print(currentLocation.latitude);
print(currentLocation.longitude);
});
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed PATHText $_counter the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}