Flutter谷歌地点搜索插件flutter_google_places_web的使用
Flutter Google Places Web
A web designed form field for Google Places Autocomplete
API Key
To use this library, you need a Web API key. Here
Usage
FlutterGooglePlacesWeb
is a Google Places Autocomplete field for Flutter Web.
import 'package:flutter_google_places_web/flutter_google_places_web.dart';
FlutterGooglePlacesWeb(
apiKey: <GOOGLE_API_KEY>,
proxyURL: 'https://cors-anywhere.herokuapp.com/',
components: 'country:us',
),
If you encounter XMLHttpRequest errors, please use a proxy. For more information, please see cors-anywhere.
If you are using the demo CORS Anywhere proxy (included in the example) - please allow temporary access or use your own proxy
If a user types and selects “1600 Amphitheatre Parkway,” you can retrieve the data as follows:
String name = FlutterGooglePlacesWeb.value['name'];
String streetAddress = FlutterGooglePlacesWeb.value['streetAddress'];
String city = FlutterGooglePlacesWeb.value['city'];
String country = FlutterGooglePlacesWeb.value['country'];
print(name); // '1600 Amphitheatre Parkway, Mountain View, CA, USA'
print(streetAddress); // '1600 Amphitheatre Parkway'
print(city); // 'CA'
print(country); // 'USA'
Roadmap
- [Coming soon] Add multiplatform support and remove CORS issues by having a JavaScript API rather than HTTP requests
Example
Here is a complete example of how to use FlutterGooglePlacesWeb
in a Flutter application:
import 'package:flutter/material.dart';
import 'package:flutter_google_places_web/flutter_google_places_web.dart';
const kGoogleApiKey = "YOUR_API_KEY";
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Google Places Web',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String test = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Google Places Web'),
),
body: Center(
child: Container(
padding: EdgeInsets.only(top: 150),
width: 500,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Address autocomplete',
style: TextStyle(fontSize: 20),
),
FlutterGooglePlacesWeb(
apiKey: kGoogleApiKey,
proxyURL: 'https://cors-anywhere.herokuapp.com/',
required: true,
),
SizedBox(height: 20),
TextButton(
onPressed: () {
final place = FlutterGooglePlacesWeb.value;
if (place != null) {
print(place['name']); // '1600 Amphitheatre Parkway, Mountain View, CA, USA'
print(place['streetAddress']); // '1600 Amphitheatre Parkway'
print(place['city']); // 'Mountain View'
print(place['country']); // 'USA'
setState(() {
test = place['name'] ?? '';
});
}
},
child: Text('Press to test'),
),
SizedBox(height: 20),
Text(
test,
style: TextStyle(fontSize: 18),
),
],
),
),
),
);
}
}
Notes
- Replace
YOUR_API_KEY
with your actual Google Places API key. - Ensure that the API key has the necessary permissions to access the Google Places API.
- If you encounter CORS issues, consider setting up your own proxy server or using a different proxy service.
This example demonstrates how to integrate the FlutterGooglePlacesWeb
widget into a Flutter application, allowing users to search for and select addresses from the Google Places API. The selected address details are then displayed on the screen.
更多关于Flutter谷歌地点搜索插件flutter_google_places_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter谷歌地点搜索插件flutter_google_places_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用 flutter_google_places_web
插件在 Flutter Web 应用中实现谷歌地点搜索的示例代码。这个插件允许你在 Flutter Web 应用中集成谷歌地点搜索功能。
首先,确保你已经在 pubspec.yaml
文件中添加了 flutter_google_places_web
依赖:
dependencies:
flutter:
sdk: flutter
flutter_google_places_web: ^0.x.x # 请使用最新版本号
然后,运行 flutter pub get
来获取依赖。
接下来,在你的 Flutter Web 应用中实现谷歌地点搜索功能。以下是一个完整的示例:
import 'package:flutter/material.dart';
import 'package:flutter_google_places_web/flutter_google_places_web.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Google Places Web Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: GooglePlacesScreen(),
);
}
}
class GooglePlacesScreen extends StatefulWidget {
@override
_GooglePlacesScreenState createState() => _GooglePlacesScreenState();
}
class _GooglePlacesScreenState extends State<GooglePlacesScreen> {
final GooglePlaces _googlePlaces = GooglePlaces(apiKey: 'YOUR_API_KEY');
List<Prediction> _predictions = [];
Future<void> _searchPlaces(String query) async {
try {
PredictionResult predictionResult = await _googlePlaces.autocomplete(query);
setState(() {
_predictions = predictionResult.predictions!;
});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Places Search'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: InputDecoration(
labelText: 'Search for a place',
border: OutlineInputBorder(),
),
onChanged: (query) {
_searchPlaces(query);
},
),
SizedBox(height: 16),
Expanded(
child: _predictions.isEmpty
? Center(child: Text('No predictions found'))
: ListView.builder(
itemCount: _predictions.length,
itemBuilder: (context, index) {
Prediction prediction = _predictions[index];
return ListTile(
title: Text(prediction.description!),
onTap: () {
// Handle the selected prediction, e.g., get place details
print('Selected: ${prediction.description}');
},
);
},
),
),
],
),
),
);
}
}
在上面的代码中,我们做了以下几件事:
- 创建一个
GooglePlaces
实例,并传入你的谷歌地点搜索 API 密钥。 - 在
GooglePlacesScreen
中,定义一个_predictions
列表来存储搜索预测结果。 - 使用
TextField
来接受用户输入,并在输入变化时调用_searchPlaces
函数进行搜索。 - 在
_searchPlaces
函数中,使用autocomplete
方法获取预测结果,并更新_predictions
列表。 - 使用
ListView.builder
来显示预测结果列表,每个预测结果都是一个ListTile
,用户点击时可以处理选中的预测(例如,获取详细信息)。
请确保将 'YOUR_API_KEY'
替换为你的实际谷歌地点搜索 API 密钥。
这个示例展示了如何在 Flutter Web 应用中使用 flutter_google_places_web
插件进行地点搜索,并显示搜索结果。你可以根据需要进一步扩展和自定义这个示例。