Flutter云数据库搜索插件firestore_search_input的使用

Flutter云数据库搜索插件firestore_search_input的使用

在本教程中,我们将详细介绍如何使用 firestore_search_input 插件来实现一个简单的云数据库搜索功能。该插件可以帮助你快速实现搜索功能,而无需手动编写大量的搜索逻辑。

确保在项目中使用 firestore_core

首先,确保在你的项目中添加了 firestore_core 依赖。这将帮助你与 Cloud Firestore 进行交互。

依赖 cloud_firestoreget

确保在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  cloud_firestore: ^4.3.1
  get: ^4.6.5

功能概述

firestore_search_input 包含以下主要功能:

  • 搜索AppBar - 一个可转换为 TextInputFieldAppBar,用于接收用户的搜索查询。
  • 搜索体 - 用户开始输入时显示的界面。
  • Cloud Firestore 查询 - 接收用户输入并查询指定的 Cloud Firestore 集合。
  • 此包是 firestore_search 的升级版
  • 感谢 Asad Hameed

简单用法

要使用此插件,只需将其添加到你的 pubspec.yaml 文件中作为依赖项即可。

dependencies:
  firestore_search: ^版本号

实现步骤

  1. 导入必要的库:
import 'package:firestore_search/firestore_search.dart';
  1. 创建一个数据模型类,并包含一个方法,用于将 QuerySnapshot 转换为对象列表。
class Book {
  final String? name;
  final String? developer;
  final String? framework;
  final String? tool;

  Book({this.name, this.developer, this.framework, this.tool});

  // 将 QuerySnapshot 转换为 Book 对象列表
  List<Book> dataListFromSnapshot(QuerySnapshot querySnapshot) {
    return querySnapshot.docs.map((snapshot) {
      final Map<String, dynamic> dataMap = snapshot.data() as Map<String, dynamic>;

      return Book(
          name: dataMap['name'],
          developer: dataMap['developer'],
          framework: dataMap['framework'],
          tool: dataMap['tool']);
    }).toList();
  }
}
  1. 使用 FirestoreSearchScaffold 并提供所需的参数。
Expanded(
  child: FirestoreSearchScaffold(
    textCapitalization: TextCapitalization.characters,
    backButtonColor: Colors.blue,
    firestoreCollectionName: 'books',
    searchBy: 'title',
    scaffoldBody: Center(),
    dataListFromSnapshot: Book().dataListFromSnapshot,

    builder: (context, snapshot) {
      print(snapshot.error);

      if (snapshot.hasData) {
        final List<Book>? dataList = snapshot.data;
        if (dataList!.isEmpty) {
          return const Center(
            child: Text('No Results Returned'),
          );
        }
        return ListView.builder(
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              final Book data = dataList[index];

              return InkWell(
                onTap: () {
                  print('searched id ${data.id}');
                  Navigator.pop(context, '${data.id}');
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        data.name ?? '',
                        style: Theme.of(context).textTheme.headline6,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8.0, left: 8.0, right: 8.0),
                      child: Text(data.developer ?? '', style: Theme.of(context).textTheme.bodyText1),
                    )
                  ],
                ),
              );
            });
      }

      if (snapshot.connectionState == ConnectionState.done) {
        if (!snapshot.hasData) {
          return const Center(
            child: Text('No Results Returned'),
          );
        }
      }
      return const Center(
        child: CircularProgressIndicator(),
      );
    },
  ),
),

完整示例

以下是完整的示例代码:

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

class Book {
  final String? name;
  final String? developer;
  final String? framework;
  final String? tool;

  Book({this.name, this.developer, this.framework, this.tool});

  List<Book> dataListFromSnapshot(QuerySnapshot querySnapshot) {
    return querySnapshot.docs.map((snapshot) {
      final Map<String, dynamic> dataMap = snapshot.data() as Map<String, dynamic>;

      return Book(
          name: dataMap['name'],
          developer: dataMap['developer'],
          framework: dataMap['framework'],
          tool: dataMap['tool']);
    }).toList();
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Firestore Search Example')),
        body: Expanded(
          child: FirestoreSearchScaffold(
            textCapitalization: TextCapitalization.characters,
            backButtonColor: Colors.blue,
            firestoreCollectionName: 'books',
            searchBy: 'title',
            scaffoldBody: Center(),
            dataListFromSnapshot: Book().dataListFromSnapshot,

            builder: (context, snapshot) {
              print(snapshot.error);

              if (snapshot.hasData) {
                final List<Book>? dataList = snapshot.data;
                if (dataList!.isEmpty) {
                  return const Center(
                    child: Text('No Results Returned'),
                  );
                }
                return ListView.builder(
                    itemCount: dataList.length,
                    itemBuilder: (context, index) {
                      final Book data = dataList[index];

                      return InkWell(
                        onTap: () {
                          print('searched id ${data.id}');
                          Navigator.pop(context, '${data.id}');
                        },
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text(
                                data.name ?? '',
                                style: Theme.of(context).textTheme.headline6,
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(bottom: 8.0, left: 8.0, right: 8.0),
                              child: Text(data.developer ?? '', style: Theme.of(context).textTheme.bodyText1),
                            )
                          ],
                        ),
                      );
                    });
              }

              if (snapshot.connectionState == ConnectionState.done) {
                if (!snapshot.hasData) {
                  return const Center(
                    child: Text('No Results Returned'),
                  );
                }
              }
              return const Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


firestore_search_input 是一个用于在 Flutter 应用中实现 Firestore 数据库搜索的插件。它允许用户通过输入框搜索 Firestore 集合中的文档,并将搜索结果实时展示在应用中。

安装

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

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

然后运行 flutter pub get 来安装插件。

使用步骤

  1. 导入包:在 Dart 文件中导入 firestore_search_input 插件。

    import 'package:firestore_search_input/firestore_search_input.dart';
    
  2. 初始化 Firestore:确保你已经初始化了 Firestore。如果你使用的是 Firebase,你需要在 main.dart 中初始化 Firebase。

    import 'package:firebase_core/firebase_core.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
  3. 使用 FirestoreSearchInput 组件:在需要搜索的地方使用 FirestoreSearchInput 组件。

    class SearchPage extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Firestore Search'),
          ),
          body: FirestoreSearchInput(
            collection: 'your_collection_name',  // Firestore 集合名称
            searchBy: 'field_name',  // 要搜索的字段名称
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final documents = snapshot.data!.docs;
                return ListView.builder(
                  itemCount: documents.length,
                  itemBuilder: (context, index) {
                    final document = documents[index];
                    return ListTile(
                      title: Text(document['field_name']),  // 显示字段值
                    );
                  },
                );
              } else if (snapshot.hasError) {
                return Center(child: Text('Error: ${snapshot.error}'));
              } else {
                return Center(child: CircularProgressIndicator());
              }
            },
          ),
        );
      }
    }
    

参数说明

  • collection: Firestore 集合的名称。
  • searchBy: 要搜索的字段名称。
  • builder: 构建搜索结果的小部件。它接收一个 AsyncSnapshot<QuerySnapshot> 对象,你可以根据 snapshot 的状态来显示加载指示器、错误信息或搜索结果。

示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 firestore_search_input 插件:

import 'package:flutter/material.dart';
import 'package:firestore_search_input/firestore_search_input.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

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

class SearchPage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Firestore Search'),
      ),
      body: FirestoreSearchInput(
        collection: 'users',  // Firestore 集合名称
        searchBy: 'name',  // 要搜索的字段名称
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final documents = snapshot.data!.docs;
            return ListView.builder(
              itemCount: documents.length,
              itemBuilder: (context, index) {
                final document = documents[index];
                return ListTile(
                  title: Text(document['name']),  // 显示字段值
                );
              },
            );
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}
回到顶部