Flutter全能索引插件omniindex的使用

Flutter 全能索引插件 OmniIndex 的使用

OmniIndex/omniindex Dart 包

OmniIndex Corporate logo on white background
  • 📒 OmniIndex Homomorphic Blockchain
  • 🏫 Postgres Machine Learning
  • 🏄‍♀️ 简单表面 API
  • 🐦 在 LinkedIn 关注我们

预备条件

简介

OmniIndex Dart 包是一个库,用于处理 OmniIndex 客户端与其在 Flutter/Dart 应用程序环境中的相关数据之间的通信。

开始使用

安装
使用此包作为库

设置你的依赖项:

使用 Dart:

dart pub add omniindex

使用 Flutter:

flutter pub add omniindex

这将在你的 pubspec.yaml 文件中添加如下行(并运行隐式的 dart pub get):

dependencies:
  omniindex:^1.0.0

或者,你的编辑器可能支持 dart pub getflutter pub get。请查看你编辑器的文档以了解更多。

现在,在你的 Dart 代码中,你可以导入并使用该包:

import 'package:omniindex/omniindex.dart';
使用
  1. 通过环境变量文件或其他安全来源提供详细信息来创建你的构造函数。切勿硬编码这些值。

    * [@param](/user/param) String apiServer (服务器地址)
    * [@param](/user/param) String seedNode (种子节点)
    * [@param](/user/param) String nodeServer (节点服务器)
    * [@param](/user/param) String localDomain (公司域)
    
  2. 一旦你有了这些参数,你可以在你的 Flutter/Dart 项目中包含 OmniIndex 包:

    import 'package:omniindex/omniindex.dart';
    
  3. 接下来,使用构造函数详细信息创建一个已连接的 OmniIndex 实例(oidx),并对其进行操作。

    示例:

    // 实例化默认值
    OmniIndex oidx = OmniIndex(debug: true);
    

    示例代码:

    /// fetchInfo 函数接受参数 [select] 和 [from] 以及一个 Map<String, String>[details] 来操作。
    Future<dynamic> fetchInfo(String select, String from, Map<String, String> details) async {
        dynamic jResponse = [];
    
        String query = "SELECT $select FROM .$from;";
    
        String body = jsonEncode(<String, dynamic>{
        "showEmptyFields": "false",
        "analyticQuery": query,
        //"showProtected": "true",
        "user": details["uid"],
        "unitName": details["email"]
        });
    
        // 接受默认构造函数。值是通过配置 JSON 文件建立的
        // 请参阅 README.md
        OmniIndex oidx = OmniIndex();
        String response = await oidx.callOmni('runanalyticqueryml', body, user);
    
        jResponse = jsonDecode(response);
        List<dynamic> res = jResponse['results'];
    
        return ((res.length == 0) ? 0 : ((select != '*') ? res.last[select] : jResponse['results']));
    }
    
    // 设置我们的详细信息
    Map<String, String> details;
    details['email'] = 'some@example.com';
    details['uid'] = 's123456789Id';
       
    // 获取高度数据并存储在我们的 details Map 中
    await fetchInfo('height', 'profile where height != 0',  details).then((height) => details['height'] = height);
    
    // 验证/操作来自 details['height'] 的高度
    

开发

API

示例代码

/// 3-Clause BSD License
/// Copyright 2023 OmniIndex Inc.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
///    this list of conditions and the following disclaimer.
/// 2. Redistributions in binary form must reproduce the above copyright notice,
///    this list of conditions and the following disclaimer in the documentation
///    and/or other materials provided with the distribution.
/// 3. Neither the name of the copyright holder nor the names of its
///    contributors may be used to endorse or promote products derived from this
///    software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
/// [@author](/user/author): Ken Hawkins
/// [@email](/user/email): ken@omniindex.io
/// [@date](/user/date): 01/24/2023
/// [@project](/user/project): omniindex
///
/// 命名约定与 Google Dart 编程规范一致。
library omniindex.example;

import 'dart:convert';
import 'dart:io';

import 'package:logger/logger.dart';
import 'package:omniindex/omniindex.dart';

final _logger = Logger(
    printer: PrettyPrinter(
  methodCount: 0,
  errorMethodCount: 5,
  lineLength: 50,
  colors: true,
  printEmojis: true,
  printTime: true,
));

OmniIndex _getOmniIndexInstance() {
  PGBCCredentials pgbcCredentials = PGBCCredentials(
      username: '[Username]',
      password: '[Password]',
      dataSource: '',
      seed: '0.0.0.0',
      port: 5434);

  return OmniIndex.withPGBCCredentials(pgbcCredentials: pgbcCredentials);
}

Future<void> main() async {
  // omniindex (oidx) 对象进行操作
  OmniIndex oidx = _getOmniIndexInstance();

  if (!await oidx.authorize()) {
    _logger.e("could not log in");
    exit;
  }

  // 用户进行操作
  BasicCredentials testUser = BasicCredentials(
      username: 'test@omniindex.io', password: 'test@omniindex.io');

  // 添加用户
  String result = await oidx.addUser(testUser.username, testUser.password);

  // 解析响应
  Map<String, dynamic> json = jsonDecode(result) as Map<String, dynamic>;

  if (json.containsKey('error')) {
    _logger.e(json);
    _logger.e('exiting...');
    exit;
  }

  // 简单删除用户
  result = await oidx.deleteUser(testUser.username);

  json = jsonDecode(result) as Map<String, dynamic>;

  _logger.d(json);

  // 退出
  _logger.d('exiting...');

  exit;
}

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

1 回复

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


当然,关于Flutter全能索引插件omniindex的使用,下面是一个基本的代码案例来展示如何集成和使用该插件。请注意,实际使用中可能会根据具体需求进行更多的配置和定制。

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

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

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用omniindex

  1. 初始化OmniIndex

在你的主页面或需要搜索功能的页面中,初始化OmniIndex实例。

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  OmniIndex? _omniIndex;

  @override
  void initState() {
    super.initState();
    // 初始化OmniIndex实例
    _omniIndex = OmniIndex(
      // 配置你的数据源和索引字段等
      items: [
        // 示例数据,可以是任何你想要搜索的对象
        {'id': 1, 'name': 'Apple', 'description': 'A fruit'},
        {'id': 2, 'name': 'Banana', 'description': 'Another fruit'},
        {'id': 3, 'name': 'Orange', 'description': 'A citrus fruit'},
      ],
      keys: ['name', 'description'],  // 指定用于搜索的字段
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('OmniIndex Demo'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextField(
                decoration: InputDecoration(
                  labelText: 'Search',
                  suffixIcon: IconButton(
                    icon: Icon(Icons.clear),
                    onPressed: () {
                      // 清空搜索框内容(这里假设有一个控制器controller)
                      // controller.clear();
                      // 重新设置搜索结果(如果需要的话)
                    },
                  ),
                ),
                onChanged: (query) {
                  // 根据用户输入实时搜索
                  setState(() {
                    // 假设有一个列表用于显示搜索结果
                    // searchResults = _omniIndex!.search(query);
                  });
                },
              ),
              // 显示搜索结果的地方(这里假设有一个ListView.builder)
              // Expanded(
              //   child: ListView.builder(
              //     itemCount: searchResults.length,
              //     itemBuilder: (context, index) {
              //       return ListTile(
              //         title: Text(searchResults[index]['name']),
              //       );
              //     },
              //   ),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}

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

注意:上面的代码是一个简化的示例,实际的搜索逻辑(如更新搜索结果列表)需要根据你的具体需求来实现。你需要自己管理一个用于显示搜索结果的列表(如searchResults),并在TextFieldonChanged回调中更新它。

  1. 搜索功能

TextFieldonChanged回调中,你可以调用_omniIndex!.search(query)来获取匹配的结果,并更新你的UI来显示这些结果。

List<Map<String, dynamic>> searchResults = [];

TextField(
  decoration: InputDecoration(
    labelText: 'Search',
    suffixIcon: IconButton(
      icon: Icon(Icons.clear),
      onPressed: () {
        // 清空搜索框和搜索结果
        controller.clear(); // 假设你有一个TextEditingController controller
        setState(() {
          searchResults.clear();
        });
      },
    ),
  ),
  controller: controller, // 绑定一个TextEditingController以便管理文本输入
  onChanged: (query) {
    setState(() {
      // 使用OmniIndex进行搜索并更新搜索结果
      searchResults = _omniIndex!.search(query);
    });
  },
),

在这个例子中,controller是一个TextEditingController的实例,你需要在State类中创建并初始化它。

请根据你的具体需求调整上述代码。omniindex插件提供了强大的搜索功能,但具体的实现细节将取决于你的应用和数据结构。

回到顶部