Flutter数据存储与同步插件etebase_flutter的使用

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

Flutter数据存储与同步插件etebase_flutter的使用

etebase_flutter

CI/CD for etebase_flutter Pub Version

Flutter平台插件,用于libetebase的Dart绑定。

目录

目录生成于markdown-toc

功能

  • Flutter插件扩展了etebase包。
  • 包含Android、iOS、macOS和Windows的捆绑库
    • Linux也受支持,通过pkg-config
  • 自动初始化etebase与flutter。

安装

只需将etebase_flutter添加到pubspec.yaml文件中并运行dart pub get(或flutter pub get)。

dart pub add etebase_flutter

注意: 纯Dart用户应使用etebase包。

使用

库初始化

要初始化库,你无需执行任何操作,因为库会通过WidgetsFlutterBinding.ensureInitialized()自动初始化。

但是,你需要创建并管理一个EtebaseClient实例。我建议使用依赖注入,例如使用riverpod来管理客户端:

final etebaseClientProvider = FutureProvider(
  (ref) => EtebaseClient.create('my-client'),
);

// ...

Widget build(BuildContext context, WidgetRef ref) =>
  ref.watch(etebaseClientProvider).when(
    loading: () => const CircularProgressIndicator(),
    error: (err, stack) => Text('Error: $err'),
    data: (client) {
      return Text("Client is ready!");
    },
  );

对于库使用的其他信息,请参阅etebase包。

Linux平台设置

在Linux上工作时,你可以选择使用pkg-config来解析libetebase而不是使用捆绑库。这将导致Linux构建链接到系统库,前提是它已安装。

要启用此模式,只需在编译前设置LIBETEBASE_USE_PKGCONFIG环境变量为非空值。例如:

export LIBETEBASE_USE_PKGCONFIG=1
flutter clean # 推荐以确保无缓存的构建工件
flutter build linux

文档

文档可以在https://pub.dev/documentation/etebase_flutter/latest/找到。基本示例可以在https://pub.dev/packages/etebase_flutter/example找到。此外,etebase包本身具有用于API一般使用的额外文档。

此外,你还可以参考官方Etebase文档。由于API尽可能接近地重现了Rust-API,你可以参考该文档中的Rust示例。大多数这些示例可以轻松应用于Dart代码。


示例代码

// ignore_for_file: avoid_print

import 'package:flutter/material.dart';

import 'package:etebase_flutter/etebase_flutter.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('etebase flutter plugin'),
        ),
        body: Center(
          child: FutureBuilder(
              future: _validateClient(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text('etebase默认服务器URL: ${snapshot.data}');
                } else if (snapshot.hasError) {
                  print('${snapshot.error}\n${snapshot.stackTrace}');
                  return Text('${snapshot.error}\n${snapshot.stackTrace}');
                } else {
                  return const CircularProgressIndicator();
                }
              }),
        ),
      ),
    );
  }

  Future<String> _validateClient() async {
    final client = await EtebaseClient.create('etebase_flutter_example');
    try {
      final serverUrl = await etebaseGetDefaultServerUrl();
      final serverIsOk = await client.checkEtebaseServer();
      if (serverIsOk) {
        return serverUrl.toString();
      } else {
        print('服务器无效');
        return "服务器无效";
      }
    } finally {
      await client.dispose();
    }
  }
}

更多关于Flutter数据存储与同步插件etebase_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据存储与同步插件etebase_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用etebase_flutter插件进行数据存储与同步的示例代码。etebase_flutter 是一个用于在Flutter应用中实现端到端加密数据存储和同步的插件。

前提条件

  1. 确保你已经在你的Flutter项目中添加了etebase_flutter依赖。
  2. 你需要在你的项目中配置网络权限,因为同步数据需要网络连接。

添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  etebase_flutter: ^x.y.z  # 替换为最新版本号

初始化Etebase客户端

首先,你需要初始化Etebase客户端。这通常包括创建或加载一个账户,并获取一个客户端实例。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Etebase Flutter Example'),
        ),
        body: EtebaseExample(),
      ),
    );
  }
}

class EtebaseExample extends StatefulWidget {
  @override
  _EtebaseExampleState createState() => _EtebaseExampleState();
}

class _EtebaseExampleState extends State<EtebaseExample> {
  late EtebaseClient client;

  @override
  void initState() {
    super.initState();
    initEtebaseClient();
  }

  Future<void> initEtebaseClient() async {
    try {
      // 初始化客户端
      client = await EtebaseClient.create();
      // 你可以在这里加载或创建账户
      // await client.createAccount('your-email@example.com', 'password');
      // 或者加载已有账户
      // await client.loadAccount('your-account-id', 'password');

      // 假设账户已经初始化,这里只是示例
      // 你可以根据需要添加账户初始化的逻辑
      setState(() {});
    } catch (e) {
      print('Error initializing Etebase client: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          // 示例按钮,实际功能需要根据你的需求实现
          // 比如同步数据、存储数据等
        },
        child: Text('Use Etebase'),
      ),
    );
  }
}

存储数据

接下来,我们展示如何存储数据。假设我们要存储一个简单的键值对。

Future<void> storeData() async {
  try {
    // 创建一个新的集合(类似于数据库中的表)
    Collection collection = await client.getOrCreateCollection('my_collection');

    // 创建一个新的文档(类似于数据库中的记录)
    Map<String, dynamic> documentData = {
      'name': 'John Doe',
      'age': 30,
    };
    Document document = await collection.createDocument(documentData);

    print('Document created: ${document.id}');
  } catch (e) {
    print('Error storing data: $e');
  }
}

同步数据

etebase_flutter会自动处理数据的同步,但你需要确保客户端已经正确初始化并且网络连接可用。

读取数据

最后,我们展示如何读取数据。

Future<void> readData() async {
  try {
    // 获取已存在的集合
    Collection collection = await client.getCollection('my_collection');

    // 获取所有文档
    List<Document> documents = await collection.getDocuments();

    for (Document document in documents) {
      print('Document: ${document.toJson()}');
    }
  } catch (e) {
    print('Error reading data: $e');
  }
}

完整示例

将上述功能整合到一个完整的示例中:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Etebase Flutter Example'),
        ),
        body: EtebaseExample(),
      ),
    );
  }
}

class EtebaseExample extends StatefulWidget {
  @override
  _EtebaseExampleState createState() => _EtebaseExampleState();
}

class _EtebaseExampleState extends State<EtebaseExample> {
  late EtebaseClient client;

  @override
  void initState() {
    super.initState();
    initEtebaseClient();
  }

  Future<void> initEtebaseClient() async {
    try {
      client = await EtebaseClient.create();
      // 你可以在这里加载或创建账户
      // await client.createAccount('your-email@example.com', 'password');
      // await client.loadAccount('your-account-id', 'password');
      setState(() {});
    } catch (e) {
      print('Error initializing Etebase client: $e');
    }
  }

  Future<void> storeData() async {
    try {
      Collection collection = await client.getOrCreateCollection('my_collection');
      Map<String, dynamic> documentData = {'name': 'John Doe', 'age': 30};
      Document document = await collection.createDocument(documentData);
      print('Document created: ${document.id}');
    } catch (e) {
      print('Error storing data: $e');
    }
  }

  Future<void> readData() async {
    try {
      Collection collection = await client.getCollection('my_collection');
      List<Document> documents = await collection.getDocuments();
      for (Document document in documents) {
        print('Document: ${document.toJson()}');
      }
    } catch (e) {
      print('Error reading data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: storeData,
          child: Text('Store Data'),
        ),
        ElevatedButton(
          onPressed: readData,
          child: Text('Read Data'),
        ),
      ],
    );
  }
}

注意:上述代码是简化示例,实际使用中需要处理更多的错误情况和用户交互。此外,你需要在适当的位置(如应用启动时)初始化Etebase客户端,并确保账户已经加载或创建。

回到顶部