mmkv在dart中的使用
Dart端
pubspec.yaml
dependencies:
mmkv: ">=1.2.8"
...
ios
为了避免与iOS上的本地库名称“ libMMKV.so”冲突,我们需要将插件名称“ mmkv”更改为“ mmkvflutter”。
对于纯flutter应用程序,请将此功能fix_mmkv_plugin_name()添加到ios / Podfile,在调用任何flutter_xxx()函数之前先调用它。 运行pod install。
def fix_mmkv_plugin_name(flutter_application_path)
is_module = false
plugin_deps_file = File.expand_path(File.join(flutter_application_path, '..', '.flutter-plugins-dependencies'))
if not File.exists?(plugin_deps_file)
is_module = true;
plugin_deps_file = File.expand_path(File.join(flutter_application_path, '.flutter-plugins-dependencies'))
end
plugin_deps = JSON.parse(File.read(plugin_deps_file)).dig('plugins', 'ios') || []
plugin_deps.each do |plugin|
if plugin['name'] == 'mmkv' || plugin['name'] == 'mmkvflutter'
require File.expand_path(File.join(plugin['path'], 'tool', 'mmkvpodhelper.rb'))
mmkv_fix_plugin_name(flutter_application_path, is_module)
return
end
end
raise "找不到任何mmkv插件依赖项。 如果您是手动运行Pod安装,请确保先执行flutter pub get"
end
fix_mmkv_plugin_name(File.dirname(File.realpath(__FILE__)))
要将flutter用作现有iOS App的模块,请将上面的功能fix_mmkv_plugin_name()添加到iOS App的Podfile中,在调用任何flutter_xxx()函数之前先调用它。 运行pod install,我们就准备好了。
def fix_mmkv_plugin_name(flutter_application_path)
.....
end
flutter_application_path = 'path/to/your/flutter_module'
fix_mmkv_plugin_name(flutter_application_path)
Android
如果您以前在Android应用中使用com.tencent.mmkv,则应转到com.tencent.mmkv-static。 并且,如果您的应用程序依赖于嵌入com.tencent.mmkv的任何第三个SDK,则可以将以下行添加到build.gradle中,以避免发生冲突:
dependencies {
...
modules {
module("com.tencent:mmkv") {
replacedBy("com.tencent:mmkv-static", "Using mmkv-static for flutter")
}
}
}
使用
import 'package:mmkv/mmkv.dart';
void main() async {
// must wait for MMKV to finish initialization
final rootDir = await MMKV.initialize();
print('MMKV for flutter with rootDir = $rootDir');
runApp(MyApp());
}
import 'package:mmkv/mmkv.dart';
var mmkv = MMKV.defaultMMKV();
mmkv.encodeBool('bool', true);
print('bool = ${mmkv.decodeBool('bool')}');
mmkv.encodeInt32('int32', (1<<31) - 1);
print('max int32 = ${mmkv.decodeInt32('int32')}');
mmkv.encodeInt('int', (1<<63) - 1);
print('max int = ${mmkv.decodeInt('int')}');
String str = 'Hello Flutter from MMKV';
mmkv.encodeString('string', str);
print('string = ${mmkv.decodeString('string')}');
str = 'Hello Flutter from MMKV with bytes';
var bytes = MMBuffer.fromList(Utf8Encoder().convert(str));
mmkv.encodeBytes('bytes', bytes);
bytes.destroy();
bytes = mmkv.decodeBytes('bytes');
print('bytes = ${Utf8Decoder().convert(bytes.asList())}');
bytes.destroy();