Flutter地点搜索插件google_places_for_flutter的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter地点搜索插件google_places_for_flutter的使用

安装

pubspec.yaml文件中添加以下依赖:

dependencies:
  google_places_for_flutter: ^1.0.0

或者直接通过命令行添加:

flutter pub add google_places_for_flutter

使用

首先,确保你已经在Google Cloud Console中创建了一个项目,并启用了Google Places API。获取你的API密钥并将其填入代码中。

示例代码

以下是一个完整的示例代码,展示了如何使用google_places_for_flutter插件来实现地点搜索功能:

import 'package:flutter/material.dart';
import 'package:google_places_for_flutter/google_places_for_flutter.dart';
import 'dart:async';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Completer<GoogleMapController> _controller = Completer();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Center(
          child: SearchGooglePlacesWidget(
            apiKey: 'Your Google Map API Key goes here', // 请替换为你的API密钥
            // 自动补全语言
            language: 'en',
            // 用于提供更好建议的位置。这里我们使用用户位置
            radius: 30000,
            onSelected: (Place place) async {
              final geolocation = await place.geolocation;

              // 将GoogleMap相机动画化,将我们带到选定的位置,并以适当的缩放级别显示
              final GoogleMapController controller = await _controller.future;
              controller.animateCamera(CameraUpdate.newLatLng(geolocation!.coordinates));
              controller.animateCamera(CameraUpdate.newLatLngBounds(geolocation.bounds, 0));
            },
            onSearch: (Place place) {},
          ),
        ),
      ),
    );
  }
}

更多关于Flutter地点搜索插件google_places_for_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地点搜索插件google_places_for_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 google_places_for_flutter 插件在 Flutter 应用中实现地点搜索的示例代码。这个插件允许你访问 Google Places API,从而搜索地点、获取地点详情等。

首先,确保你已经在 pubspec.yaml 文件中添加了 google_places_for_flutter 依赖:

dependencies:
  flutter:
    sdk: flutter
  google_places_for_flutter: ^0.3.0  # 请检查最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,在你的 Flutter 应用中,你需要进行以下步骤:

  1. 设置 API 密钥

    android/app/src/main/AndroidManifest.xmlios/Runner/Info.plist 中设置你的 Google Places API 密钥。对于 Android,你可以添加如下代码:

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY"/>
    

    对于 iOS,你需要在 Info.plist 中添加一个键值对:

    <key>GOOGLE_API_KEY</key>
    <string>YOUR_API_KEY</string>
    
  2. 初始化插件并进行搜索

    在你的 Dart 代码中,你可以这样使用 google_places_for_flutter 插件:

    import 'package:flutter/material.dart';
    import 'package:google_places_for_flutter/google_places_for_flutter.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      TextEditingController _controller = TextEditingController();
      List<Prediction> _predictions = [];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Google Places Search'),
          ),
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: <Widget>[
                TextField(
                  controller: _controller,
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.search),
                    hintText: 'Search for a place',
                  ),
                  onChanged: (value) {
                    _fetchPredictions(value);
                  },
                ),
                SizedBox(height: 16.0),
                Expanded(
                  child: _predictions.isEmpty
                      ? Center(child: CircularProgressIndicator())
                      : ListView.builder(
                          itemCount: _predictions.length,
                          itemBuilder: (context, index) {
                            return ListTile(
                              title: Text(_predictions[index].description),
                              onTap: () {
                                // Handle place selection
                                _getPlaceDetails(_predictions[index].placeId);
                              },
                            );
                          },
                        ),
                ),
              ],
            ),
          ),
        );
      }
    
      Future<void> _fetchPredictions(String query) async {
        setState(() {
          _predictions = [];
        });
    
        if (query.isNotEmpty) {
          final Predictions predictions = await PlacesAutocomplete.show(
            context: context,
            apiKey: 'YOUR_API_KEY',
            mode: Mode.fullscreen,
            language: "en",
            components: [Component(Component.country, "us")],
          );
    
          setState(() {
            _predictions = predictions.predictions;
          });
        }
      }
    
      Future<void> _getPlaceDetails(String placeId) async {
        final PlaceDetails place = await PlacesAutocomplete.getPlaceDetailsByPlaceId(
          placeId: placeId,
          apiKey: 'YOUR_API_KEY',
        );
    
        // Handle the place details, e.g., show them in a snack bar or navigate to a new screen
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Place ID: ${place.placeId}, Name: ${place.name}'),
          ),
        );
      }
    }
    

在这个示例中,我们创建了一个简单的 Flutter 应用,它包含一个文本字段用于输入搜索查询。当用户输入内容时,会调用 _fetchPredictions 方法,该方法使用 PlacesAutocomplete.show 方法显示一个自动完成对话框。用户选择某个预测后,会调用 _getPlaceDetails 方法获取该地点的详细信息,并在 snack bar 中显示。

请确保替换 'YOUR_API_KEY' 为你自己的 Google Places API 密钥。此外,你可能需要根据你的应用需求调整组件和样式。

回到顶部