What the heck is that?
Glad you asked! (docs are work in progress, but the libraries are stable.)
Multiplatform key-value store is like any other key value store, but it's multiplatform. Badum-tss!
This repo contains three different folders. Each of them is a Dart package project.
The key_value_store
package defines common key-value storage APIs in an abstract way without caring about the implementation.
You might ask what is the point for this, and that is an entirely valid question!
When you're doing code sharing across Flutter and the web, you can't import platform specific dependencies in your core business logic components.
Using localStorage
for web or SharedPreferences
for Flutter in your pure business logic is a no-no.
Here's how you would use the abstract class in your common business logic:
import 'package:key_value_store/key_value_store.dart';
class MyBusinessLogic {
MyBusinessLogic(this.kvs);
final KeyValueStore kvs;
void storeHelloMessage(String name) {
final result = 1 + 2; // Real world is more complicated - this is just a sample.
kvs.setString('message', 'Hello, $name! Did you know that 1 + 2 is $result?');
}
}
This implements the abstract class defined in key_value_store
with Flutter-specific implementation.
In this case, using SharedPreferences
.
To use, pass it SharedPreferences
from the shared_preferences Flutter plugin package:
import 'package:key_value_store_flutter/key_value_store_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
final prefs = await SharedPreferences.getInstance();
final kvs = FlutterKeyValueStore(prefs);
...
// Pass the Flutter specific key-value store to MyBusinessLogic!
final myBusinessLogic = MyBusinessLogic(kvs);
This is also an implementation of the interface defined in the key_value_store
package.
Pass it window.localStorage
or window.sessionStorage
from the dart:html
package and you're good to go:
import 'package:key_value_store_web/key_value_store_web.dart';
import 'dart:html';
final kvs = WebKeyValueStore(window.localStorage);
...
// Pass the web specific key-value store to MyBusinessLogic!
final myBusinessLogic = MyBusinessLogic(kvs);