Flutter地点自动完成插件google_location_autocomplete_textfield_flutter的使用

google_location_autocomplete_textfield_flutter #

添加依赖到pubspec.yml #

dependencies:
  flutter:
    sdk: flutter
  google_location_autocomplete_textfield_flutter: <last-version>

谷歌自动完成文本框小部件代码 #

GoogleLocationAutoCompleteTextField(
  textEditingController: controller, // 文本控制器
  googleAPIKey: "YOUR_GOOGLE_API_KEY", // 谷歌地图API密钥
  inputDecoration: InputDecoration(), // 输入框装饰器
  debounceTime: 800, // 防抖时间,默认600ms
  countries: ["in", "fr"], // 可选参数,默认为null
  isLatLngRequired: true, // 是否需要经纬度信息
  getPlaceDetailWithLatLng: (Prediction prediction) {
    // 返回带有经纬度的地方详情
    print("placeDetails" + prediction.lat.toString());
  }, // 当isLatLngRequired为true时调用的回调函数
  itemClick: (Prediction prediction) {
    // 点击列表项时触发
    controller.text = prediction.description ?? "";
    controller.selection = TextSelection.fromPosition(
      TextPosition(offset: prediction.description?.length ?? 0)
    );
  },
  
  // 如果要自定义列表项构建器
  itemBuilder: (context, index, Prediction prediction) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        children: [
          Icon(Icons.location_on), // 图标
          SizedBox(width: 7), // 空白间距
          Expanded(child: Text("${prediction.description ?? ""}")) // 地点描述
        ],
      ),
    );
  },
  
  // 如果需要在列表项之间添加分隔符
  separatedBuilder: Divider(),
  
  // 是否显示关闭按钮
  isCrossBtnShown: true,
  
  // 容器水平内边距
  containerHorizontalPadding: 10,
  
  // 地点类型
  placeType: PlaceType.geocode,
)

定制选项 #

您可以自定义输入框的装饰器和防抖时间。

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:google_location_autocomplete_textfield_flutter/google_location_autocomplete_textfield.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: '自动完成示例'),
    );
  }
}

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

  final String? title;

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

class _MyHomePageState extends State<MyHomePage> {
  late TextEditingController controller;

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title ?? ""),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(height: 20),
            placesAutoCompleteTextField(),
          ],
        ),
      ),
    );
  }

  Widget placesAutoCompleteTextField() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20),
      child: GoogleLocationAutoCompleteTextField(
        textEditingController: controller,
        googleAPIKey: "YOUR_GOOGLE_API_KEY",
        inputDecoration: InputDecoration(
          hintText: "搜索您的位置",
          border: InputBorder.none,
          enabledBorder: InputBorder.none,
        ),
        debounceTime: 400, // 防抖时间
        countries: ["in", "fr"], // 国家限制
        isLatLngRequired: true, // 是否需要经纬度
        getPlaceDetailWithLatLng: (Prediction prediction) {
          print("placeDetails" + prediction.lat.toString());
        },
        itemClick: (Prediction prediction) {
          controller.text = prediction.description ?? "";
          controller.selection = TextSelection.fromPosition(
            TextPosition(offset: prediction.description?.length ?? 0)
          );
        },
        separatedBuilder: Divider(),
        containerHorizontalPadding: 10,
        itemBuilder: (context, index, Prediction prediction) {
          return Container(
            padding: EdgeInsets.all(10),
            child: Row(
              children: [
                Icon(Icons.location_on),
                SizedBox(width: 7),
                Expanded(child: Text("${prediction.description ?? ""}"))
              ],
            ),
          );
        },
        isCrossBtnShown: true,
      ),
    );
  }
}

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

1 回复

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


google_location_autocomplete_textfield_flutter 是一个用于在 Flutter 应用中实现地点自动完成功能的插件。它基于 Google Places API,允许用户输入地点名称并自动完成,从而方便地选择地点。

安装插件

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

dependencies:
  flutter:
    sdk: flutter
  google_location_autocomplete_textfield_flutter: ^1.0.0

然后运行 flutter pub get 来安装依赖。

获取 Google Places API 密钥

要使用这个插件,你需要一个 Google Places API 密钥。你可以通过以下步骤获取:

  1. 前往 Google Cloud Console
  2. 创建一个新项目或选择一个现有项目。
  3. 启用 Places API
  4. API & Services > Credentials 中创建一个 API 密钥。

使用插件

在你的 Flutter 应用中使用 GoogleLocationAutocompleteTextField 组件来实现地点自动完成功能。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Location Autocomplete Example'),
        ),
        body: LocationAutocompleteExample(),
      ),
    );
  }
}

class LocationAutocompleteExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: GoogleLocationAutocompleteTextField(
        apiKey: 'YOUR_GOOGLE_PLACES_API_KEY', // 替换为你的 Google Places API 密钥
        onSelected: (Place place) {
          print('Selected place: ${place.description}');
          // 你可以在这里处理选中的地点
        },
        hintText: 'Enter a location',
      ),
    );
  }
}

参数说明

  • apiKey: 你的 Google Places API 密钥。
  • onSelected: 当用户选择一个地点时触发的回调函数。Place 对象包含地点的详细信息,如 descriptionplaceId 等。
  • hintText: 输入框的提示文本。

处理选中的地点

onSelected 回调中,你可以处理用户选择的地点。Place 对象通常包含以下信息:

  • description: 地点的描述(通常是地址)。
  • placeId: 地点的唯一标识符,可以用于获取更多详细信息。

获取地点详细信息

如果你需要获取地点的更多详细信息(如经纬度、地址组件等),你可以使用 placeId 调用 Google Places API 的 Place Details 接口。

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> fetchPlaceDetails(String placeId, String apiKey) async {
  final url = 'https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$apiKey';
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    final result = data['result'];
    print('Place details: $result');
  } else {
    throw Exception('Failed to load place details');
  }
}
回到顶部