Flutter地点搜索与选择插件google_places_flutter的使用

Flutter地点搜索与选择插件 google_places_flutter 的使用

添加依赖到 pubspec.yaml

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

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

请确保将 <last-version> 替换为最新版本号。

Google 自动补全文本框组件代码

下面是一个使用 GooglePlaceAutoCompleteTextField 组件的示例代码,该组件允许用户通过输入位置名称来搜索和选择地点:

import 'package:flutter/material.dart';
import 'package:google_places_flutter/google_places_flutter.dart';
import 'package:google_places_flutter/model/place_type.dart';
import 'package:google_places_flutter/model/prediction.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(title: 'Custom Autocomplete sample'),
    );
  }
}

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

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController controller = TextEditingController();

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

  placesAutoCompleteTextField() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20),
      child: GooglePlaceAutoCompleteTextField(
        textEditingController: controller,
        googleAPIKey: "YOUR_GOOGLE_API_KEY",
        inputDecoration: InputDecoration(
          hintText: "Search your location",
          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));
        },
        seperatedBuilder: 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,
      ),
    );
  }
}

定制选项

你可以自定义文本框的输入装饰(inputDecoration)和防抖时间(debounceTime)。例如:

inputDecoration: InputDecoration(
  hintText: "Search your location",
  border: InputBorder.none,
  enabledBorder: InputBorder.none,
),
debounceTime: 400,

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

1 回复

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


当然,以下是如何在Flutter项目中使用google_places_flutter插件进行地点搜索与选择的示例代码。

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

dependencies:
  flutter:
    sdk: flutter
  google_places_flutter: ^0.14.0  # 请确保使用最新版本

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

接下来,你需要配置API密钥。在Google Cloud Platform上启用Places API,并获取API密钥。然后,在android/app/src/main/AndroidManifest.xml中添加API密钥:

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

同样地,在ios/Runner/Info.plist中,你需要添加以下内容来允许网络请求:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

现在,你可以在Flutter代码中使用google_places_flutter插件。以下是一个简单的示例,展示如何进行地点搜索和选择:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Google Places Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PlaceSearchScreen(),
    );
  }
}

class PlaceSearchScreen extends StatefulWidget {
  @override
  _PlaceSearchScreenState createState() => _PlaceSearchScreenState();
}

class _PlaceSearchScreenState extends State<PlaceSearchScreen> {
  final PlacesClient _placesClient = PlacesClient(apiKey: 'YOUR_API_KEY_HERE');
  TextEditingController _searchController = 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(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: 'Search for a place...',
                suffixIcon: IconButton(
                  icon: Icon(Icons.clear),
                  onPressed: () {
                    _searchController.clear();
                    setState(() {
                      _predictions = [];
                    });
                  },
                ),
              ),
              onEditingComplete: _handleSearch,
            ),
            Expanded(
              child: _predictions.isEmpty
                  ? Center(child: Text('No predictions found'))
                  : ListView.builder(
                      itemCount: _predictions.length,
                      itemBuilder: (context, index) => ListTile(
                        title: Text(_predictions[index].description),
                        onTap: () {
                          // Handle place selection
                          _getPlaceDetails(_predictions[index].placeId);
                        },
                      )),
            ),
          ],
        ),
      ),
    );
  }

  void _handleSearch() async {
    if (_searchController.text.isNotEmpty) {
      PredictionResult predictionsResult = await _placesClient.autocompleteQuery(
        _searchController.text,
        components: [Component(Component.CountryCode, "us")],  // Optional: restrict search to a country
      );

      if (predictionsResult.status == PlacesAutocompleteStatus.ok) {
        setState(() {
          _predictions = predictionsResult.predictions;
        });
      }
    }
  }

  void _getPlaceDetails(String placeId) async {
    PlaceDetailsResult placeDetailsResult = await _placesClient.getPlaceDetails(placeId);

    if (placeDetailsResult.status == PlacesStatus.ok) {
      PlaceDetails place = placeDetailsResult.result;
      // Handle place details here
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(place.name),
          content: Text(place.formattedAddress ?? 'No address available'),
          actions: <Widget>[
            FlatButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      );
    }
  }
}

在上面的代码中:

  1. 我们创建了一个简单的Flutter应用,包含一个搜索栏和一个用于显示预测结果的ListView。
  2. 当用户完成输入时,_handleSearch方法会被调用,该方法使用autocompleteQuery方法来获取预测结果。
  3. 预测结果会显示在ListView中,用户可以点击某个预测项来获取详细地点信息。
  4. _getPlaceDetails方法使用getPlaceDetails方法来获取并显示详细地点信息。

请确保将YOUR_API_KEY_HERE替换为你自己的Google Places API密钥。

这个示例代码展示了如何使用google_places_flutter插件进行地点搜索和选择,但你可以根据需要进行进一步的自定义和扩展。

回到顶部