Flutter 中获取地理位置[Flutter专题]
import 'package:flutter/material.dart';
import 'package:location/location.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Location location = Location();
String _currentLocation = 'Unknown';
void getLocation() async {
try {
LocationData locationData = await location.getLocation();
if (locationData != null) {
setState(() {
_currentLocation =
'Latitude: ${locationData.latitude}, '
'Longitude: ${locationData.longitude}';
});
}
} catch (e) {
print('Could not get location: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Get Location Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Current Location:'),
Text(_currentLocation),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getLocation,
tooltip: 'Get Location',
child: Icon(Icons.my_location),
),
);
}
}
这段代码使用了location
插件来获取设备的当前位置。用户可以点击浮动按钮触发位置获取,然后位置数据会显示在屏幕上。这是一个简单的示例,展示了如何在Flutter应用中集成和使用位置服务。
评论已关闭