Flutter快速同步客户端插件fast_sync_client的使用

Flutter快速同步客户端插件fast_sync_client的使用

快速同步简介





FastSync 是一个强大的简化数据同步的包,它通过将多个 API 整合到一个统一的接口中来简化从服务器端到客户端应用的数据同步。

受 Git 版本控制方法的启发,FastSync 提供了一组功能以提供高效的数据同步解决方案:

  • pull()
  • push()
  • sync()
  • hardReset()

FastSync 通过智能处理由于远程更改引起的冲突,超越了传统的同步工具。我们的高级冲突检测机制在对象级别识别冲突,使用户能够提供自定义的解决函数。

FastSync 支持三种不同的冲突解决策略以适应各种用例:

  • LastWriterWins
  • TimestampOrdering
  • PredefinedRules

注意:当你指定为预定义规则时,你需要在每次检测到冲突时提供一个自定义的解决函数。


客户端安装

dependencies:
  # 添加 fast_sync_client 到你的依赖项
  fast_sync_client:
  # 添加 fast_sync_hive_dao 到你的依赖项
  fast_sync_hive_dao:

dev_dependencies:
  # 添加生成器到你的 dev_dependencies
  build_runner:

客户端设置

  1. 在你的应用程序的主函数中初始化 FastSync 包。
  2. 配置你的 DAO(数据访问对象),在初始化 FastSync 包时,我们使用 Hive DAO 作为示例。
  3. 使用 setSyncableObject 方法配置要同步的对象类型,并为该类型设置同步区域字符串。
  4. 初始化该类型的 DataSource 和 Repository。
  5. 为配置的对象类型配置冲突处理器。
  6. 配置 httpManager,使用它可以与服务器交互,在这里你需要实现 push 和 pull 函数。

示例代码:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initHive();
  FastSync.setSyncConfiguration<HiveSyncConfiguration>(HiveSyncConfiguration());
  FastSync.setTypeSyncZone<Item>(SyncZoneRestrictionEnum.restricted, syncZone: "userId");
  FastSync.setHttpManager(HttpManager());
  ItemRepository repository = ItemRepository(dataSource: ItemDataSource());
  FastSync.setSyncableObject<Item>(
      fromJson: Item.fromJson, toJson: Item.intoJson, repository: repository);
  runApp(MyApp());
}

Future<void> initHive() async {
  var dir = await getApplicationDocumentsDirectory();
  Hive.init(dir.path);
  Hive.registerAdapter(ItemAdapter());
}

客户端同步对象

import 'package:fast_sync_hive_dao/fast_sync_hive_dao.dart';
import 'package:hive/hive.dart';
import 'package:json_annotation/json_annotation.dart';
part 'item.g.dart';

@HiveType(typeId: 1, adapterName: "ItemAdapter")
@JsonSerializable(explicitToJson: true)
class Item extends SyncableItemModel {
  @HiveField(1)
  String name;

  @HiveField(2)
  String description;

  Item({required this.name, required this.description});

  @override
  factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$ItemToJson(this);

  static Function get intoJson => _$ItemToJson;
}

运行代码生成器

运行生成器命令:

flutter packages pub run build_runner build

为了自动运行生成器,当文件发生变化时,可以使用:

flutter packages pub run build_runner watch

客户端同步对象数据源

import 'package:example/item/item.dart';
import 'package:fast_sync_hive_dao/fast_sync_hive_dao.dart';

class ItemDataSource extends SyncalbeObjectDataSource<Item> {
  ItemDataSource();
}

客户端同步对象仓库

import 'package:example/item/item.dart';
import 'package:fast_sync_client/fast_sync_client.dart';

class ItemRepository extends SyncalbeRepository<Item> {
  ItemRepository({required super.dataSource});
}

HTTP管理器

import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:fast_sync_client/fast_sync_client.dart';

class HttpManager implements IhttpManager {
  final dio = Dio();
  HttpManager();

  @override
  Future<SyncPayload> pull(SyncOperationMetadata metadata) async {
    Response response = await dio.post(
        'https://www.server.com/pull',
        data: json.encode(metadata.toJson()));
    if (response.data["success"] == true) {
      return SyncPayload.fromJson(response.data["data"]);
    }
    return throw Exception('pull failed');
  }

  @override
  Future<bool> push(SyncPayload payload) async {
    Response response = await dio.post(
        'https://www.server.com/push',
        data: json.encode(payload.toJson()));
    if (response.data["success"] == true) {
      return true;
    }
    return throw Exception('push failed');
  }
}

同步管理器

import 'package:example/item/item.dart';
import 'package:fast_sync_client/fast_sync_client.dart';
import 'package:flutter/material.dart';

class ItemProvider with ChangeNotifier {
  List<Item> items = [];
  ISyncableRepository<Item> repository = FastSync.getObjectRepository<Item>();
  ISyncManager syncManager = FastSync.getSyncManager();

  Future<List<Item>> loadLocalItems() async {
    List<Item> localItems = await repository.getAll();
    return localItems;
  }

  Future<void> pull() async {
    await syncManager.pull();
  }

  Future<void> sync() async {
    await syncManager.sync();
  }

  Future<void> push() async {
    await syncManager.push();
  }

  Future<void> hardReset() async {
    await syncManager.hardReset();
  }

  Future<void> resetItemRepo() async {
    await repository.hardDelete();
  }

  Future<Item> saveElement(Item item) async {
    item = await repository.add(item);
    return item;
  }

  Future<Item> updateElement(Item item) async {
    item = await repository.update(item);
    return item;
  }

  Future<int> getCount() async {
    int count = await repository.count();
    return count;
  }
}

更多关于Flutter快速同步客户端插件fast_sync_client的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter快速同步客户端插件fast_sync_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


fast_sync_client 是一个用于 Flutter 的插件,旨在提供高效的数据同步功能,允许开发者在客户端和服务器之间快速同步数据。它适用于需要在本地和远程数据库之间保持数据一致性的应用场景。

以下是使用 fast_sync_client 插件的基本步骤和示例:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 fast_sync_client 依赖:

dependencies:
  flutter:
    sdk: flutter
  fast_sync_client: ^0.1.0  # 请使用最新版本

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

2. 初始化插件

在应用的入口处(通常是 main.dart),初始化 FastSyncClient

import 'package:fast_sync_client/fast_sync_client.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 FastSyncClient
  await FastSyncClient.initialize(
    baseUrl: 'https://your-server-url.com', // 服务器地址
    syncInterval: Duration(minutes: 5),     // 同步间隔时间
    conflictResolutionPolicy: ConflictResolutionPolicy.serverWins, // 冲突解决策略
  );
  
  runApp(MyApp());
}

3. 定义数据模型

定义一个数据模型类,并使用 @FastSync 注解标记该类为可同步的实体:

import 'package:fast_sync_client/fast_sync_client.dart';

@FastSync()
class Task {
  String id;
  String title;
  bool isCompleted;

  Task({required this.id, required this.title, this.isCompleted = false});
}

4. 同步数据

使用 FastSyncClient 进行数据同步。例如,可以在应用启动时或在用户执行某些操作时触发同步:

import 'package:fast_sync_client/fast_sync_client.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fast Sync Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 手动触发同步
              await FastSyncClient.instance.sync();
            },
            child: Text('Sync Data'),
          ),
        ),
      ),
    );
  }
}

5. 处理冲突

fast_sync_client 提供了多种冲突解决策略,如 serverWinsclientWinscustom 等。你可以根据需要选择合适的策略,或在 custom 策略中实现自定义的冲突处理逻辑。

await FastSyncClient.initialize(
  baseUrl: 'https://your-server-url.com',
  syncInterval: Duration(minutes: 5),
  conflictResolutionPolicy: ConflictResolutionPolicy.custom(
    resolveConflict: (localData, remoteData) {
      // 自定义冲突解决逻辑
      return remoteData; // 例如,总是使用远程数据
    },
  ),
);

6. 监控同步状态

你可以监听同步状态的变化,以便在 UI 中显示同步进度或错误信息:

FastSyncClient.instance.syncStatusStream.listen((status) {
  print('Sync status: $status');
});

7. 调试与日志

fast_sync_client 提供了调试日志功能,可以通过设置 debugLogEnabled 来启用:

FastSyncClient.initialize(
  baseUrl: 'https://your-server-url.com',
  syncInterval: Duration(minutes: 5),
  debugLogEnabled: true,
);
回到顶部