Flutter谷歌搜索功能插件google_search_api的使用

Flutter 谷歌搜索功能插件 google_search_api 的使用

特性

  • 使用谷歌服务搜索谷歌地点。

开始前

在开始使用此插件之前,请确保阅读并创建一个谷歌开发者控制台中的 API 密钥。

使用 Dart 添加插件

$ dart pub add google_search_api

在 Flutter 中添加插件

$ flutter pub add google_search_api

使用示例

首先,你需要导入 google_search_api 包:

import 'package:google_search_api/google_search_api.dart';

接下来,你可以使用以下代码来搜索附近的餐厅:

void searchNearbyPlaces() async {
  try {
    // 创建 GoogleSearchParametersModle 实例
    // 参数依次为:查询关键字(如 'cruise'),经纬度(如 '-33.8670522,151.1957362'),API 密钥(如 'YOUR_API_KEY'),搜索半径(单位米,如 1500 米),类型(如 'restaurant')
    GoogleSearchParametersModle googleSearchParametersModle = GoogleSearchParametersModle(
      'cruise', 
      '-33.8670522,151.1957362', 
      'YOUR_API_KEY', 
      1500, 
      'restaurant'
    );

    // 调用 getNearbyPlaces 方法获取搜索结果
    dynamic places = await getNearbyPlaces(googleSearchParametersModle);

    // 打印搜索结果
    if (kDebugMode) {
      print(places.results);
    }
  } catch (e) {
    // 捕获并打印异常信息
    if (kDebugMode) {
      print(e);
    }
  }
}

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

1 回复

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


在Flutter中使用google_search_api插件来实现谷歌搜索功能,你需要按照以下步骤进行操作。google_search_api插件允许你通过Google Custom Search API来执行搜索查询并获取结果。

1. 安装依赖

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

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

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

2. 获取Google Custom Search API密钥和搜索引擎ID

要使用Google Custom Search API,你需要一个API密钥和一个搜索引擎ID。你可以通过以下步骤获取:

  1. 创建Google Cloud项目:如果你还没有Google Cloud项目,请先创建一个。
  2. 启用Custom Search API:在Google Cloud控制台中,找到并启用Custom Search API。
  3. 获取API密钥:在API和服务中,创建一个API密钥。
  4. 创建自定义搜索引擎:访问Google Custom Search Engine并创建一个新的搜索引擎,获取搜索引擎ID。

3. 使用google_search_api进行搜索

在你的Flutter应用中,你可以使用google_search_api来执行搜索并获取结果。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Google Search API Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SearchPage(),
    );
  }
}

class SearchPage extends StatefulWidget {
  [@override](/user/override)
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final String apiKey = 'YOUR_API_KEY';  // 替换为你的API密钥
  final String searchEngineId = 'YOUR_SEARCH_ENGINE_ID';  // 替换为你的搜索引擎ID
  List<SearchResult> searchResults = [];
  TextEditingController searchController = TextEditingController();

  Future<void> search(String query) async {
    GoogleSearch search = GoogleSearch(apiKey, searchEngineId);
    SearchResponse response = await search.search(query);

    setState(() {
      searchResults = response.items ?? [];
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Search'),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: searchController,
              decoration: InputDecoration(
                labelText: 'Search',
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () {
                    search(searchController.text);
                  },
                ),
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: searchResults.length,
              itemBuilder: (context, index) {
                SearchResult result = searchResults[index];
                return ListTile(
                  title: Text(result.title ?? 'No Title'),
                  subtitle: Text(result.snippet ?? 'No Snippet'),
                  onTap: () {
                    // 处理点击事件,例如打开链接
                    if (result.link != null) {
                      // 使用url_launcher插件打开链接
                      // launch(result.link!);
                    }
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
回到顶部