Flutter地点搜索插件google_places_sdk_text_field的使用

Flutter 地点搜索插件 google_places_sdk_text_field 的使用

简介

此插件提供了一个完全可自定义的自动完成文本字段。该插件使用 flutter-google-places-sdk 来获取预测数据。

使用

示例演示

简单的使用方式:

GooglePlacesSdkTextField(
  apiKey: 'your_api_key_here',
  countries: const ['nz', 'us'],
  fetchPlace: true,
  fetchPlaceFields: const [
    PlaceField.Location,
    PlaceField.Address,
  ],
  onPlaceSelected: (prediction, place) {
    // 在此处处理选中的预测或位置
  },
);

API 密钥是必需的。如需了解如何获取它,请参阅 flutter-google-places-sdk 文档。你还可以传递参数给 SDK 包。大多数 TextField 参数也受支持。

更复杂的使用方式:

GooglePlacesSdkTextField(
  apiKey: '_your_API_key',
  countries: const ['nz', 'us'],
  fetchPlace: true,
  fetchPlaceFields: const [
    PlaceField.Location,
    PlaceField.Address,
  ],
  decoration: InputDecoration(
    border: border,
    focusedBorder: border.copyWith(
      borderSide: const BorderSide(width: 2),
    ),
    fillColor: Colors.green.shade100,
    filled: true,
  ),
  clearIcon: const Icon(
    Icons.exit_to_app,
    color: Colors.green,
  ),
  loadingWidget: LinearProgressIndicator(
    color: Colors.green.shade700,
  ),
  onPlaceSelected: (prediction, place) {
    // 在此处处理选中的预测或位置
  },
  placesBuilder: (predictions, onPredictionSelected) {
    return ListView(
      padding: EdgeInsets.zero,
      shrinkWrap: true,
      children: predictions.map((prediction) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.green.shade100,
            borderRadius: BorderRadius.circular(4),
          ),
          padding: const EdgeInsets.all(4),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.green.shade200,
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.bottomRight,
            padding: const EdgeInsets.all(8),
            child: Text(prediction.primaryText),
          ),
        );
      }).toList(),
    );
  }),

构建器

placesBuilder - 用于表示找到的预测的 UI。结果小部件将显示在 TextField 下方的覆盖层中。它提供了两个参数:

  • predictions - 要显示的预测列表。
  • onPredictionSelected - 当在结果小部件内选择预测时应调用此回调。主 onPlaceSelected 回调将被调用(如果 fetchPlace 为真,则会获取位置)。

属性

  • apiKey - Google 地点 API 密钥。这是必需的。
  • fetchPlace - 指示是否应该获取 Google 地点信息(一旦预测被选中)。
  • locale - 地点 API 响应将被本地化的语言环境。
  • countries - 如果不为空,则结果将限制在这些国家。
  • delayMs - 文本变化去抖动的延迟时间(以毫秒为单位)。
  • fetchPlaceFields - 当 fetchPlace 为真时,则仅返回请求的字段。如果没有指定,则返回所有字段。
  • decoration - TextField 装饰覆盖。请注意,suffixIcon 将被覆盖。你可以通过覆盖 clearIcon 进行自定义。

此外,还支持大多数标准 TextField 属性。

可以自定义的小部件列表:

  • clearIcon - 表示清除图标小部件。
  • loadingWidget - 表示在获取预测时的加载小部件。

更多信息

有关最近更改的详细信息,请参阅 CHANGELOG

致谢

许可证

该插件采用 MIT 许可证。更多详情请参阅 许可证文件

完整示例

import 'package:flutter/material.dart';
import 'package:google_places_sdk_text_field/google_places_sdk_text_field.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _apiKey = '_your_API_key_here_';
  String _selectedPlace = '';

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final border = OutlineInputBorder(
      borderRadius: BorderRadius.circular(12),
      borderSide: BorderSide(
        color: Colors.green.shade700,
      ),
    );
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Example'),
        ),
        body: SafeArea(
          child: SizedBox(
            width: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text('开始搜索(普通模式)...'),
                FractionallySizedBox(
                  widthFactor: 0.75,
                  child: GooglePlacesSdkTextField(
                    apiKey: _apiKey,
                    countries: const ['nz', 'us'],
                    fetchPlace: true,
                    fetchPlaceFields: const [
                      PlaceField.Location,
                      PlaceField.Address,
                    ],
                    onPlaceSelected: (prediction, place) => setState(
                      () => _selectedPlace = place!.address!,
                    ),
                  ),
                ),
                const Padding(
                  padding: EdgeInsets.only(top: 64),
                  child: Text('开始搜索(自定义模式)...'),
                ),
                FractionallySizedBox(
                  widthFactor: 0.75,
                  child: GooglePlacesSdkTextField(
                      apiKey: _apiKey,
                      countries: const ['nz', 'us'],
                      fetchPlace: true,
                      fetchPlaceFields: const [
                        PlaceField.Location,
                        PlaceField.Address,
                      ],
                      decoration: InputDecoration(
                        border: border,
                        focusedBorder: border.copyWith(
                          borderSide: const BorderSide(width: 2),
                        ),
                        fillColor: Colors.green.shade100,
                        filled: true,
                      ),
                      clearIcon: const Icon(
                        Icons.exit_to_app,
                        color: Colors.green,
                      ),
                      loadingWidget: LinearProgressIndicator(
                        color: Colors.green.shade700,
                      ),
                      onPlaceSelected: (prediction, place) => setState(
                            () => _selectedPlace = place!.address!,
                          ),
                      placesBuilder: (predictions, onPredictionSelected) {
                        return ListView(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          children: predictions.map((prediction) {
                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.green.shade100,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              padding: const EdgeInsets.all(4),
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.green.shade200,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                alignment: Alignment.bottomRight,
                                padding: const EdgeInsets.all(8),
                                child: Text(prediction.primaryText),
                              ),
                            );
                          }).toList(),
                        );
                      }),
                ),
                Padding(
                  padding: const EdgeInsets.all(32),
                  child: Text(
                    _selectedPlace,
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


google_places_sdk_text_field 是一个 Flutter 插件,用于集成 Google Places SDK 的地点搜索功能。它提供了一个文本字段,用户可以在其中输入地点,并从 Google Places API 获取自动完成的建议。以下是如何使用这个插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 google_places_sdk_text_field 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  google_places_sdk_text_field: ^1.0.0  # 请检查最新版本

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

2. 获取 Google Places API 密钥

你需要一个 Google Places API 密钥来使用这个插件。你可以从 Google Cloud Console 获取 API 密钥。确保启用了 Places API。

3. 初始化插件

在你的 Dart 文件中,导入插件并初始化它。你需要在 main.dart 或任何其他初始化代码中配置 API 密钥:

import 'package:flutter/material.dart';
import 'package:google_places_sdk_text_field/google_places_sdk_text_field.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Google Places SDK Text Field Example'),
        ),
        body: PlacesSearchWidget(),
      ),
    );
  }
}

class PlacesSearchWidget extends StatefulWidget {
  @override
  _PlacesSearchWidgetState createState() => _PlacesSearchWidgetState();
}

class _PlacesSearchWidgetState extends State<PlacesSearchWidget> {
  final String apiKey = 'YOUR_GOOGLE_PLACES_API_KEY';

  @override
  Widget build(BuildContext context) {
    return GooglePlacesSdkTextField(
      apiKey: apiKey,
      onPlaceSelected: (Place place) {
        // 处理选中的地点
        print('Selected place: ${place.name}');
        print('Latitude: ${place.latLng.latitude}, Longitude: ${place.latLng.longitude}');
      },
    );
  }
}

4. 处理选中的地点

当用户选择一个地点时,onPlaceSelected 回调会被触发。你可以在这个回调中处理选中的地点信息。Place 对象包含了地点的名称、经纬度等信息。

5. 自定义外观

你可以通过传递 decoration 参数来自定义文本字段的外观:

GooglePlacesSdkTextField(
  apiKey: apiKey,
  onPlaceSelected: (Place place) {
    // 处理选中的地点
  },
  decoration: InputDecoration(
    labelText: 'Search for a place',
    border: OutlineInputBorder(),
  ),
);

6. 其他功能

google_places_sdk_text_field 插件还提供了其他一些功能,例如设置初始值、自定义提示文本等。你可以参考插件的 文档 来了解更多信息。

7. 处理错误

确保处理可能发生的错误,例如网络问题或 API 密钥无效。你可以在 onPlaceSelected 回调中添加错误处理逻辑。

GooglePlacesSdkTextField(
  apiKey: apiKey,
  onPlaceSelected: (Place place) {
    if (place != null) {
      // 处理选中的地点
    } else {
      // 处理错误
      print('Error selecting place');
    }
  },
);
回到顶部