Skip to content

Instantly share code, notes, and snippets.

@NicolasCaous
Created December 5, 2019 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicolasCaous/002b21f23f050cb77b63de632e58ed5f to your computer and use it in GitHub Desktop.
Save NicolasCaous/002b21f23f050cb77b63de632e58ed5f to your computer and use it in GitHub Desktop.
A flutter singleton async-safe example
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:hive/hive.dart';
class LocationCacheSingleton {
static LocationCacheSingleton _instance;
static Future<Null> _mutex;
// Não é thread-safe, apenas async-safe. Entretanto, como o
// flutter é single-thread, essa solução não tem problema.
static Future<LocationCacheSingleton> getInstance() async {
if (_mutex != null) {
await _mutex;
}
var completer = new Completer<Null>();
_mutex = completer.future;
if (_instance == null) {
_instance = LocationCacheSingleton();
await _instance.init();
}
completer.complete();
_mutex = null;
return _instance;
}
static String SerializeLatLng(LatLng latlng) {
ByteData bdata = ByteData.view(Uint8List(16).buffer);
bdata.setFloat64(0, latlng.latitude);
bdata.setFloat64(8, latlng.longitude);
return Base64Codec().encode(bdata.buffer.asUint8List());
}
static LatLng DeserializeLatLng(String latlng) {
ByteData bdata = ByteData.view(Base64Codec().decode(latlng).buffer);
return LatLng(bdata.getFloat64(0), bdata.getFloat64(8));
}
Box box;
LocationCacheSingleton();
Future<LocationCacheSingleton> init() async {
this.box = await Hive.openBox('location');
return this;
}
dynamic get(String key) {
return this.box.get(key);
}
Future<void> put(String key, dynamic value) async {
return await this.box.put(key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment