Flutter位置选择插件open_location_picker的使用
Flutter位置选择插件 open_location_picker
的使用
open_location_picker
是一个用于在Flutter应用中选择地理位置的插件。它支持从OpenStreetMap地图上选择单个或多个位置,并且可以与BLoC模式集成,适应暗黑主题。
特性
- 选择单个位置
- 选择多个位置
- 显示OpenStreetMap地图
- 可以与BLoC模式一起工作
- 尊重暗黑主题
开始使用
首先需要配置一些设置:
- 处理如何获取当前位置(可以使用
location
或geolocator
包,或者任何你想要的方式)
示例代码
import 'package:flutter/material.dart';
import 'package:open_location_picker/open_location_picker.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return _buildGeolocatorPackage();
}
Future<LatLng> _determinePosition() async {
// 这里应该实现获取当前位置的逻辑
// 示例中省略了具体实现
return LatLng(37.4219983, -122.084);
}
Widget _buildGeolocatorPackage() {
return OpenMapSettings(
onError: (context, error) {},
getCurrentLocation: _determinePosition,
reverseZoom: ReverseZoom.building,
getLocationStream: () => Stream.fromIterable([]),
child: MaterialApp(
title: 'Flutter Demo',
locale: const Locale("en"),
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''), // 英语,无国家代码
Locale('ar', ''), // 阿拉伯语,无国家代码
],
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.light,
home: const MyHomePage(title: 'open_location_picker demo'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(
padding: const EdgeInsets.all(20),
children: <Widget>[
OpenMapPicker(
decoration: const InputDecoration(
hintText: "My Location",
),
onSaved: (FormattedLocation? newValue) {
// 保存新值
},
),
MultiOpenMapPicker(
decoration: const InputDecoration(hintText: "My multi location"),
onSaved: (List<FormattedLocation> newValue) {
// 保存新值
},
),
],
),
),
);
}
void showPicker(BuildContext context) {
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
return OpenStreetMaps(
options: OpenMapOptions(),
bloc: CustomBloc(const OpenMapState.selected(SelectedLocation.single(null))),
);
}));
}
}
class CustomBloc extends Cubit<OpenMapState> implements OpenMapBloc {
CustomBloc(OpenMapState initialState) : super(initialState);
@override
void emit(OpenMapState state) {
super.emit(state);
}
}
使用方法
有三种方式可以使用此插件:
1. 使用 OpenMapPicker
选择单个位置
OpenMapPicker(
decoration: const InputDecoration(hintText: "My location"),
onSaved: (FormattedLocation? newValue) {
/// 保存新值
},
),
2. 使用 MultiOpenMapPicker
选择多个位置
MultiOpenMapPicker(
decoration: const InputDecoration(hintText: "My multi location"),
onSaved: (List<FormattedLocation> newValue) {
/// 保存新值
},
),
3. 自定义使用
第一步:创建自定义 BLoC
class CustomBloc extends Cubit<OpenMapState> implements OpenMapBloc {
CustomBloc(OpenMapState initialState) : super(initialState);
}
第二步:使用它
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
return OpenStreetMaps(
options: OpenMapOptions(),
bloc: CustomBloc(const OpenMapState.selected(SelectedLocation.single(null))),
);
}));
更多关于Flutter位置选择插件open_location_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter位置选择插件open_location_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用Flutter中的open_location_picker
插件的示例代码。这个插件允许用户从地图上选择一个位置,并返回该位置的详细信息,如经纬度、地址等。
首先,确保你已经在pubspec.yaml
文件中添加了open_location_picker
依赖:
dependencies:
flutter:
sdk: flutter
open_location_picker: ^0.6.0 # 请检查最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,你可以在你的Flutter应用中使用这个插件。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
import 'package:open_location_picker/open_location_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Open Location Picker Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
LocationData? _selectedLocation;
Future<void> _pickLocation() async {
final LocationData? location = await OpenLocationPicker().pickLocation(
context,
initialPosition: LatLng(37.7749, -122.4194), // 旧金山的坐标作为初始位置
useCurrentLocation: true, // 是否使用当前位置作为初始位置
selectionMode: SelectionMode.point, // 选择模式:点选择
requiredFields: [LocationFieldType.name, LocationFieldType.latLng], // 必填字段
);
if (location != null) {
setState(() {
_selectedLocation = location;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Open Location Picker Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _pickLocation,
child: Text('Pick Location'),
),
SizedBox(height: 20),
if (_selectedLocation != null)
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('Name: ${_selectedLocation!.name}'),
Text('Latitude: ${_selectedLocation!.latLng!.latitude}'),
Text('Longitude: ${_selectedLocation!.latLng!.longitude}'),
],
),
],
),
),
);
}
}
class LocationData {
final String? name;
final LatLng? latLng;
LocationData({this.name, this.latLng});
}
class LatLng {
final double latitude;
final double longitude;
LatLng(this.latitude, this.longitude);
}
注意:
-
在这个示例中,
LocationData
和LatLng
类是为了演示目的而创建的简单数据模型。在实际应用中,你应该使用open_location_picker
插件提供的LocationData
和LatLng
类。 -
OpenLocationPicker().pickLocation()
方法返回一个Future<LocationData?>
,你可以通过await
关键字等待结果。 -
在
pickLocation
方法中,你可以配置多个参数,如initialPosition
(初始位置)、useCurrentLocation
(是否使用当前位置)、selectionMode
(选择模式)和requiredFields
(必填字段)等。 -
当用户选择一个位置后,结果将存储在
_selectedLocation
变量中,并在UI中显示。
确保在实际应用中处理错误和异常,例如用户取消选择位置的情况。