Flutter地点搜索插件free_place_search的使用

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

Flutter地点搜索插件free_place_search的使用

Free Place Search

使用Photon API进行地点搜索。

Usage

以下是如何在Flutter应用中使用free_place_search插件的示例代码。

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 使用PlaceAutocomplete小部件
            PlaceAutocomplete.widget(onDone: (e) {}),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => PlaceAutocomplete.show(
            onDone: (e) {
              Navigator.pop(context);
            },
            context: context),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

完整示例代码

以下是完整的示例代码,用于展示如何在Flutter应用中集成地点搜索功能。

import 'package:flutter/material.dart';
import 'package:free_place_search/place_search.dart';

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

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 使用PlaceAutocomplete小部件
            PlaceAutocomplete.widget(onDone: (e) {}),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => PlaceAutocomplete.show(
            onDone: (e) {
              Navigator.pop(context);
            },
            context: context),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用free_place_search插件进行地点搜索的示例代码。这个插件允许你通过Google Places API进行地点搜索。

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

dependencies:
  flutter:
    sdk: flutter
  free_place_search: ^最新版本号  # 请替换为最新的版本号

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

接下来,你需要在你的Flutter项目中配置Google Places API的API密钥。确保你已经在Google Cloud Platform上启用了Places API,并获取了API密钥。

下面是一个完整的示例代码,展示了如何使用free_place_search插件:

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

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

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

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

class _PlaceSearchScreenState extends State<PlaceSearchScreen> {
  final TextEditingController _controller = TextEditingController();
  List<Prediction> _predictions = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Place Search Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: 'Search for a place...',
                suffixIcon: IconButton(
                  icon: Icon(Icons.clear),
                  onPressed: () {
                    _controller.clear();
                    setState(() {
                      _predictions = [];
                    });
                  },
                ),
              ),
              onChanged: (value) {
                _fetchPredictions(value);
              },
            ),
            SizedBox(height: 16.0),
            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 selection of a prediction
                            print('Selected: ${prediction.description}');
                            // Optionally, you can use prediction.placeId to get details of the place
                          },
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _fetchPredictions(String query) async {
    // Replace YOUR_API_KEY with your actual Google Places API key
    String apiKey = 'YOUR_API_KEY';
    PlaceSearchService placeSearchService = PlaceSearchService(apiKey: apiKey);

    try {
      AutocompletePredictionResponse response = await placeSearchService.getAutocompletePredictions(
        input: query,
        type: 'geocode', // You can specify other types like 'establishment'
        components: null, // Optional, specify a location bias
        sessionToken: null, // Optional, for session management
      );

      setState(() {
        _predictions = response.predictions ?? [];
      });
    } catch (e) {
      print('Error fetching predictions: $e');
    }
  }
}

在这个示例中:

  1. 我们创建了一个简单的Flutter应用,其中包含一个文本字段用于输入搜索查询。
  2. 当用户在文本字段中输入内容时,_fetchPredictions函数会被调用,该函数使用free_place_search插件的PlaceSearchService来获取自动完成的预测。
  3. 预测结果会显示在下方的列表中,用户可以点击列表项来处理选择。

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

这个示例演示了基本的地点搜索功能,你可以根据需求进一步扩展和优化。

回到顶部