如何使用 Flutter 和地理位置 API 构建基于位置的移动应用程序?
import 'package:flutter/material.dart';
import 'package:location/location.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// 此处可以添加必要的初始化代码
@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();
setState(() {
_currentLocation =
'Latitude: ${locationData.latitude}, Longitude: ${locationData.longitude}';
});
} catch (e) {
print('Error: $e');
setState(() {
_currentLocation = 'Failed to get location';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Location App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Current Location:'),
Text(_currentLocation),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getLocation,
tooltip: 'Get Location',
child: Icon(Icons.location_searching),
),
);
}
}
这段代码使用了Flutter的location
插件来获取设备的当前位置,并在界面上显示。用户可以点击浮动按钮来触发位置获取功能。这个例子展示了如何在Flutter应用中集成地理位置服务,并简单地处理位置数据。
评论已关闭