Flutter二进制地图文件处理插件binary_map_file的使用

Flutter二进制地图文件处理插件binary_map_file的使用

BinaryMapFile 是一个用于在纯Dart中通过文件系统进行高效键值存储的库,并且提供了安全支持。


开始使用

要开始使用该库,只需导入 binary_map_file 包:

import "dart:io";
import 'package:binary_map_file/binary_map_file.dart';

final file = File(path);
final binaryMapFile = BinaryMapFile(file, secured: false); 
await binaryMapFile.ensureInitialized();
// 如果你需要安全的序列化,可以将标志 secured 设置为 `true`

获取值

获取键 firstRun 对应的布尔值。如果该键未设置或为 null,则将其重置为默认值 true 并返回获取到的值。

final firstRun = binaryMapFile.getDefaultValue<bool>('firstRun', true); // 返回布尔值或默认值
// 或者
final value = binaryMapFile.getValue<bool>('firstRun'); // 返回布尔值或 null

设置值

将键 firstRun 的值设置为 false

binaryMapFile.setValue<bool>('firstRun', false);

检查包含键

检查是否存在键 firstRun

final existed = binaryMapFile.containsKey('firstRun');

序列化

将当前映射保存到文件:

await binaryMapFile.serialize();

支持的数据类型

该库支持所有由 Flutter 标准二进制编码使用的 MessageCodec 所支持的数据类型。支持的消息包括以下无环值:

  • null
  • bool 布尔值
  • num 数值
  • String 字符串
  • Uint8List, Int32List, Int64List, Float64List 数组
  • List 列表
  • Map 映射

示例代码

以下是完整的示例代码,展示了如何使用 BinaryMapFile 插件来管理应用中的计数器数据:

import 'dart:io';

import 'package:binary_map_file/binary_map_file.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Count will be saved into map file'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const String key = 'count';
  late final BinaryMapFile binaryMapFile;
  late final ValueNotifier<bool> initNotifier;
  late final ValueNotifier<int> countNotifier;
  int _counter = 0;

  [@override](/user/override)
  void initState() {
    super.initState();

    initNotifier = ValueNotifier<bool>(false);

    WidgetsBinding.instance.addPostFrameCallback((_) async => initialize());
  }

  Future<void> initialize() async {
    final Directory appDocumentsDir = await getApplicationDocumentsDirectory();
    final filePath = path.join(appDocumentsDir.path, 'file.dat');

    binaryMapFile = BinaryMapFile(path: filePath);
    await binaryMapFile.ensureInitialized();
    initNotifier.value = true;

    final count = binaryMapFile.getDefaultValue<int>(key, 0) ?? 0;
    countNotifier = ValueNotifier<int>(count);
  }

  Future<void> _incrementCounter() async {
    var count = binaryMapFile.getValue<int>(key) ?? 0;
    ++count;

    binaryMapFile.setValue<int>(key, count);
    await binaryMapFile.serialize();
    countNotifier.value = count;

    setState(() {
      ++_counter;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: ValueListenableBuilder(
          valueListenable: initNotifier,
          builder: (context, init, _) {
            if (!init) {
              return const Center(child: CircularProgressIndicator());
            }

            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'Increase value and hot start the app to check saved value:',
                ),
                ValueListenableBuilder(
                    valueListenable: countNotifier,
                    builder: (context, count, _) {
                      return Text(
                        '$count',
                        style: Theme.of(context).textTheme.headlineMedium,
                      );
                    }),
                const Text(
                  'This is normal counter:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
              ],
            );
          },
        ),
      ),
      floatingActionButton: ValueListenableBuilder(
          valueListenable: initNotifier,
          builder: (context, init, _) {
            if (!init) {
              return const SizedBox();
            }

            return FloatingActionButton(
              onPressed: _incrementCounter,
              tooltip: 'Increment',
              child: const Icon(Icons.add),
            );
          }),
    );
  }
}

更多关于Flutter二进制地图文件处理插件binary_map_file的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter二进制地图文件处理插件binary_map_file的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在处理Flutter应用中的二进制地图文件时,binary_map_file 插件可以帮助你读取和解析这些文件。以下是一个使用 binary_map_file 插件的示例代码,展示如何加载和处理二进制地图文件。

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

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

然后,运行 flutter pub get 来获取依赖。

接下来,下面是一个示例代码,展示如何使用 binary_map_file 插件:

import 'package:flutter/material.dart';
import 'package:binary_map_file/binary_map_file.dart'; // 假设插件提供了此导入路径
import 'dart:typed_data';
import 'dart:io';

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

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

class _MyAppState extends State<MyApp> {
  Uint8List? _mapData;
  String? _errorMessage;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Binary Map File Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: _loadAndParseMapFile,
                child: Text('Load and Parse Map File'),
              ),
              if (_errorMessage != null)
                Text(
                  'Error: $_errorMessage',
                  style: TextStyle(color: Colors.red),
                ),
              if (_mapData != null)
                Text(
                  'Map Data Loaded Successfully',
                  style: TextStyle(color: Colors.green),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _loadAndParseMapFile() async {
    setState(() {
      _errorMessage = null;
      _mapData = null;
    });

    try {
      // 假设二进制地图文件位于应用的assets目录中
      ByteData byteData = await rootBundle.load('assets/map_file.bin');
      Uint8List mapData = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);

      // 使用binary_map_file插件解析二进制地图文件
      // 假设插件提供了一个名为parseMapData的函数
      // MapFileResult result = await BinaryMapFile.parseMapData(mapData);
      // 注意:上面的代码行是假设的,具体API请参考插件文档

      // 由于没有具体API文档,这里仅展示如何存储二进制数据
      setState(() {
        _mapData = mapData;
      });

      // 在实际应用中,你可能会根据解析结果更新UI或执行其他操作
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
      });
    }
  }
}

注意

  1. 由于 binary_map_file 插件的具体API和函数名称未知,上述代码中的 BinaryMapFile.parseMapData(mapData) 是一个假设的调用。你需要查阅插件的官方文档来了解如何正确解析二进制地图文件。
  2. 确保将二进制地图文件放在 assets 目录中,并在 pubspec.yaml 文件中正确声明这些资产。
flutter:
  assets:
    - assets/map_file.bin
  1. 在实际项目中,你可能需要处理更复杂的解析逻辑和错误处理。

请查阅 binary_map_file 插件的官方文档以获取更多详细信息和API参考。

回到顶部