Browse Source

[shared_preferences] Add plugin shared_preferences

merge-requests/11/head
Vitaliy Zarubin 2 years ago
parent
commit
8adb3bfadd
  1. 32
      packages/shared_preferences/shared_preferences_aurora/.gitignore
  2. 46
      packages/shared_preferences/shared_preferences_aurora/README.md
  3. 4
      packages/shared_preferences/shared_preferences_aurora/analysis_options.yaml
  4. BIN
      packages/shared_preferences/shared_preferences_aurora/data/preview.png
  5. 45
      packages/shared_preferences/shared_preferences_aurora/example/.gitignore
  6. 22
      packages/shared_preferences/shared_preferences_aurora/example/README.md
  7. 29
      packages/shared_preferences/shared_preferences_aurora/example/analysis_options.yaml
  8. 1
      packages/shared_preferences/shared_preferences_aurora/example/aurora/.gitignore
  9. 47
      packages/shared_preferences/shared_preferences_aurora/example/aurora/CMakeLists.txt
  10. 12
      packages/shared_preferences/shared_preferences_aurora/example/aurora/desktop/com.example.shared_preferences_aurora_example.desktop
  11. 16
      packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugin_registrant.cpp
  12. 12
      packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugin_registrant.h
  13. 32
      packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugins.cmake
  14. BIN
      packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/108x108.png
  15. BIN
      packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/128x128.png
  16. BIN
      packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/172x172.png
  17. BIN
      packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/86x86.png
  18. 10
      packages/shared_preferences/shared_preferences_aurora/example/aurora/main.cpp
  19. 31
      packages/shared_preferences/shared_preferences_aurora/example/aurora/rpm/com.example.shared_preferences_aurora_example.spec
  20. 199
      packages/shared_preferences/shared_preferences_aurora/example/lib/main.dart
  21. 23
      packages/shared_preferences/shared_preferences_aurora/example/pubspec.yaml
  22. 27
      packages/shared_preferences/shared_preferences_aurora/example/test/widget_test.dart
  23. 52
      packages/shared_preferences/shared_preferences_aurora/lib/shared_preferences_aurora.dart
  24. 72
      packages/shared_preferences/shared_preferences_aurora/lib/shared_preferences_aurora_api.dart
  25. 30
      packages/shared_preferences/shared_preferences_aurora/pubspec.yaml

32
packages/shared_preferences/shared_preferences_aurora/.gitignore vendored

@ -0,0 +1,32 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.packages
build/
.metadata
run.sh

46
packages/shared_preferences/shared_preferences_aurora/README.md

@ -0,0 +1,46 @@
# shared_preferences_aurora
The Aurora implementation of [`shared_preferences`][https://pub.dev/packages/shared_preferences].
## Usage
This package is not an _endorsed_ implementation of `shared_preferences`.
Therefore, you have to include `path_provider_aurora` alongside `shared_preferences` as dependencies in your `pubspec.yaml` file.
**pubspec.yaml**
```yaml
dependencies:
shared_preferences: ^2.1.1
shared_preferences_aurora: ^0.0.0 # @todo Not published
```
***.dart**
```dart
import 'package:shared_preferences/shared_preferences.dart';
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
```

4
packages/shared_preferences/shared_preferences_aurora/analysis_options.yaml

@ -0,0 +1,4 @@
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

BIN
packages/shared_preferences/shared_preferences_aurora/data/preview.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

45
packages/shared_preferences/shared_preferences_aurora/example/.gitignore vendored

@ -0,0 +1,45 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
pubspec.lock

22
packages/shared_preferences/shared_preferences_aurora/example/README.md

@ -0,0 +1,22 @@
# shared_preferences_aurora_example
Demonstrates how to use the shared_preferences_aurora plugin.
## Build
```shell
# Add an alias if it doesn't already exist
alias flutter-aurora=$HOME/.local/opt/flutter-sdk/bin/flutter
# Get dependencies
flutter-aurora pub get
# Run build
flutter-aurora build aurora --release # [--release|--debug|--profile]
```
You can collect, sign, run an example on the device with a script located in the `script/build_example.sh`
More information in `build_example.sh`.
### Preview example
![preview.png](../data/preview.png)

29
packages/shared_preferences/shared_preferences_aurora/example/analysis_options.yaml

@ -0,0 +1,29 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

1
packages/shared_preferences/shared_preferences_aurora/example/aurora/.gitignore vendored

@ -0,0 +1 @@
flutter/ephemeral

47
packages/shared_preferences/shared_preferences_aurora/example/aurora/CMakeLists.txt

@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.10)
project(com.example.shared_preferences_aurora_example LANGUAGES CXX)
include(GNUInstallDirs)
set(BINARY_NAME ${CMAKE_PROJECT_NAME})
set(FLUTTER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/flutter)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "-Wall -Wextra")
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
set(CMAKE_SKIP_RPATH OFF)
set(CMAKE_INSTALL_RPATH "\$ORIGIN/../share/${BINARY_NAME}/lib")
find_package(PkgConfig REQUIRED)
pkg_check_modules(FlutterEmbedder REQUIRED IMPORTED_TARGET flutter-embedder)
add_executable(${BINARY_NAME} main.cpp ${FLUTTER_DIR}/generated_plugin_registrant.cpp)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::FlutterEmbedder)
target_include_directories(${BINARY_NAME} PRIVATE ${FLUTTER_DIR})
include(flutter/generated_plugins.cmake)
set(PACKAGE_INSTALL_DIR ${CMAKE_INSTALL_DATADIR}/${BINARY_NAME})
set(DESKTOP_INSTALL_DIR ${CMAKE_INSTALL_DATADIR}/applications)
set(ICONS_INSTALL_ROOT_DIR ${CMAKE_INSTALL_DATADIR}/icons/hicolor)
add_custom_command(TARGET ${BINARY_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/libflutter-embedder.so
${PROJECT_BINARY_DIR}/bundle/lib/libflutter-embedder.so)
install(FILES ${PROJECT_BINARY_DIR}/bundle/icudtl.dat DESTINATION ${PACKAGE_INSTALL_DIR})
install(DIRECTORY ${PROJECT_BINARY_DIR}/bundle/flutter_assets DESTINATION ${PACKAGE_INSTALL_DIR})
install(DIRECTORY ${PROJECT_BINARY_DIR}/bundle/lib DESTINATION ${PACKAGE_INSTALL_DIR})
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES desktop/${BINARY_NAME}.desktop DESTINATION ${DESKTOP_INSTALL_DIR})
foreach(ICONS_SIZE 86x86 108x108 128x128 172x172)
install(FILES icons/${ICONS_SIZE}.png
RENAME ${BINARY_NAME}.png
DESTINATION ${ICONS_INSTALL_ROOT_DIR}/${ICONS_SIZE}/apps/)
endforeach(ICONS_SIZE)

12
packages/shared_preferences/shared_preferences_aurora/example/aurora/desktop/com.example.shared_preferences_aurora_example.desktop

@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Name=shared_preferences_aurora_example
Comment=Demonstrates how to use the shared_preferences_aurora plugin.
Icon=com.example.shared_preferences_aurora_example
Exec=/usr/bin/com.example.shared_preferences_aurora_example
X-Nemo-Application-Type=silica-qt5
[X-Application]
Permissions=
OrganizationName=com.example
ApplicationName=shared_preferences_aurora_example

16
packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugin_registrant.cpp

@ -0,0 +1,16 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include <flutter/application.h>
#include <path_provider_aurora/path_provider_aurora_plugin.h>
#include "generated_plugin_registrant.h"
void RegisterPlugins() {
Application::RegisterPlugins({
std::make_shared<PathProviderAuroraPlugin>(),
});
}

12
packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugin_registrant.h

@ -0,0 +1,12 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT
#define GENERATED_PLUGIN_REGISTRANT
void RegisterPlugins();
#endif /* GENERATED_PLUGIN_REGISTRANT */

32
packages/shared_preferences/shared_preferences_aurora/example/aurora/flutter/generated_plugins.cmake

@ -0,0 +1,32 @@
#
# Generated file, do not edit.
#
set(ROOT_PROJECT_BINARY_DIR "${PROJECT_BINARY_DIR}")
function(add_library TARGET)
_add_library(${TARGET} ${ARGN})
if(NOT "${TARGET}" MATCHES "^PkgConfig::.*")
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"$<TARGET_FILE:${TARGET}>"
"${ROOT_PROJECT_BINARY_DIR}/bundle/lib/$<TARGET_FILE_NAME:${TARGET}>")
endif(NOT "${TARGET}" MATCHES "^PkgConfig::.*")
endfunction()
list(APPEND FLUTTER_PLATFORM_PLUGIN_LIST
path_provider_aurora
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
xdga_directories
)
foreach(PLUGIN ${FLUTTER_PLATFORM_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${PLUGIN}/aurora plugins/${PLUGIN})
target_link_libraries(${BINARY_NAME} PRIVATE ${PLUGIN}_platform_plugin)
endforeach(PLUGIN)
foreach(FFI_PLUGIN ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${FFI_PLUGIN}/aurora plugins/${FFI_PLUGIN})
endforeach(FFI_PLUGIN)

BIN
packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/108x108.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

BIN
packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/128x128.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/172x172.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
packages/shared_preferences/shared_preferences_aurora/example/aurora/icons/86x86.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

10
packages/shared_preferences/shared_preferences_aurora/example/aurora/main.cpp

@ -0,0 +1,10 @@
#include <flutter/application.h>
#include "generated_plugin_registrant.h"
int main(int argc, char *argv[]) {
Application::Initialize(argc, argv);
Application::SetPixelRatio(1.8);
RegisterPlugins();
Application::Launch();
return 0;
}

31
packages/shared_preferences/shared_preferences_aurora/example/aurora/rpm/com.example.shared_preferences_aurora_example.spec

@ -0,0 +1,31 @@
%global __provides_exclude_from ^%{_datadir}/%{name}/lib/.*$
%global __requires_exclude ^lib(dconf|flutter-embedder|maliit-glib|appmanifest-.+|.+_platform_plugin)\\.so.*$
Name: com.example.shared_preferences_aurora_example
Summary: Demonstrates how to use the shared_preferences_aurora plugin.
Version: 0.1.0
Release: 1
License: Proprietary
Source0: %{name}-%{version}.tar.zst
BuildRequires: cmake
BuildRequires: pkgconfig(flutter-embedder)
%description
%{summary}.
%prep
%autosetup
%build
%cmake -DCMAKE_BUILD_TYPE=%{_flutter_build_type}
%make_build
%install
%make_install
%files
%{_bindir}/%{name}
%{_datadir}/%{name}/*
%{_datadir}/applications/%{name}.desktop
%{_datadir}/icons/hicolor/*/apps/%{name}.png

199
packages/shared_preferences/shared_preferences_aurora/example/lib/main.dart

@ -0,0 +1,199 @@
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int? _counter;
bool? _repeat;
double? _decimal;
String? _action;
List<String>? _items;
String? _error;
@override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
try {
SharedPreferences.setPrefix("my_prefix.");
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
setState(() {
_counter = counter;
_repeat = repeat;
_decimal = decimal;
_action = action;
_items = items;
});
} on PlatformException {
setState(() {
_error = 'Platform exception';
});
}
}
@override
Widget build(BuildContext context) {
const textStyleWhite = TextStyle(fontSize: 18, color: Colors.white);
const textStyleTitle = TextStyle(fontSize: 20, color: Colors.black);
const textStylePath = TextStyle(fontSize: 18, color: Colors.black54);
const spaceMedium = SizedBox(height: 20);
const spaceSmall = SizedBox(height: 10);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Example shared_preferences'),
),
body: Stack(
children: [
// Error message
Visibility(
visible: _error != null,
child: Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Container(
padding: const EdgeInsets.all(20),
decoration: const BoxDecoration(
color: Colors.redAccent,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
child: Text(
_error ?? '',
style: textStyleWhite,
),
),
),
),
),
// List directories path
Visibility(
visible: _error == null,
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: Column(
children: [
// Info
Container(
padding: const EdgeInsets.all(20),
decoration: const BoxDecoration(
color: Colors.green,
borderRadius:
BorderRadius.all(Radius.circular(10.0)),
),
child: const Text(
'Demo application demonstration implementation of shared_preferences',
style: textStyleWhite,
textAlign: TextAlign.center,
),
),
const SizedBox(height: 30),
const Text(
'Counter / int',
style: textStyleTitle,
),
spaceSmall,
Text(
_counter.toString(),
style: textStylePath,
),
spaceMedium,
const Text(
'Repeat / bool',
style: textStyleTitle,
),
spaceSmall,
Text(
_repeat.toString(),
style: textStylePath,
),
spaceMedium,
const Text(
'Decimal / double',
style: textStyleTitle,
),
spaceSmall,
Text(
_decimal.toString(),
style: textStylePath,
),
spaceMedium,
const Text(
'Action / String',
style: textStyleTitle,
),
spaceSmall,
Text(
_action.toString(),
style: textStylePath,
),
spaceMedium,
const Text(
'Items / String List',
style: textStyleTitle,
),
spaceSmall,
Text(
_items.toString(),
style: textStylePath,
),
],
),
),
),
),
),
],
),
),
);
}
}

23
packages/shared_preferences/shared_preferences_aurora/example/pubspec.yaml

@ -0,0 +1,23 @@
name: shared_preferences_aurora_example
description: Demonstrates how to use the shared_preferences_aurora plugin.
publish_to: 'none'
environment:
sdk: '>=2.18.6 <3.0.0'
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.1.1
shared_preferences_aurora:
path: ../
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true

27
packages/shared_preferences/shared_preferences_aurora/example/test/widget_test.dart

@ -0,0 +1,27 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_aurora_example/main.dart';
void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that platform version is retrieved.
expect(
find.byWidgetPredicate(
(Widget widget) => widget is Text &&
widget.data!.startsWith('Running on:'),
),
findsOneWidget,
);
});
}

52
packages/shared_preferences/shared_preferences_aurora/lib/shared_preferences_aurora.dart

@ -0,0 +1,52 @@
import 'package:flutter/services.dart';
import 'package:path_provider_aurora/path_provider_aurora.dart';
import 'package:shared_preferences_aurora/shared_preferences_aurora_api.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:flutter/foundation.dart';
class SharedPreferencesAurora extends SharedPreferencesStorePlatform {
/// Registers this class as the default instance of [SharedPreferencesStorePlatform].
static void registerWith() {
if (TargetPlatform.aurora == defaultTargetPlatform) {
PathProviderAurora.registerWith();
SharedPreferencesStorePlatform.instance = SharedPreferencesAurora();
}
}
static const String _defaultPrefix = 'flutter.';
final SharedPreferencesAuroraApi _api =
SharedPreferencesAuroraApi('.flutter_shared_preferences.json');
@override
Future<bool> setValue(String valueType, String key, Object value) async {
switch (valueType) {
case 'String':
case 'Bool':
case 'Int':
case 'Double':
case 'StringList':
return _api.setData(key, value);
}
throw PlatformException(
code: 'InvalidOperation',
message: '"$valueType" is not a supported type.');
}
@override
Future<bool> remove(String key) async => _api.remove(key);
@override
Future<bool> clear() => clearWithPrefix(_defaultPrefix);
@override
Future<Map<String, Object>> getAll() => getAllWithPrefix(_defaultPrefix);
@override
Future<bool> clearWithPrefix(String prefix) async =>
_api.clearWithPrefix(prefix);
@override
Future<Map<String, Object>> getAllWithPrefix(String prefix) async =>
(await _api.getAllWithPrefix(prefix)).cast();
}

72
packages/shared_preferences/shared_preferences_aurora/lib/shared_preferences_aurora_api.dart

@ -0,0 +1,72 @@
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
class SharedPreferencesAuroraApi {
final JsonDecoder decoder = const JsonDecoder();
final String fileName;
SharedPreferencesAuroraApi(this.fileName);
/// Remove all data by prifix
Future<bool> clearWithPrefix(String prefix) async {
final map = await _read();
final filtered = {
for (final key in map.keys)
if (!key.startsWith(prefix)) key: map[key]
};
await _save(filtered);
return true;
}
/// Get all data by prifix
Future<Map<Object?, Object?>> getAllWithPrefix(String prefix) async {
final map = await _read();
return {
for (final key in map.keys)
if (key.startsWith(prefix)) key: map[key]
};
}
/// Remove one value
Future<bool> remove(String key) async {
final map = await _read();
if (map.containsKey(key)) {
map.remove(key);
await _save(map);
return true;
}
return false;
}
/// Add value and save data
Future<bool> setData(String key, dynamic value) async {
final map = await _read();
map[key] = value;
await _save(map);
return true;
}
/// Get file with data
Future<File> _getFile() async {
return File(p.join(
(await getTemporaryDirectory()).path,
fileName,
)).create(recursive: true);
}
/// Read file
Future<Map<String, dynamic>> _read() async {
final file = await _getFile();
final value = await file.readAsString();
return value.isEmpty ? {} : decoder.convert(value);
}
/// Save data to file
Future<void> _save(Map<String, dynamic> data) async {
final file = await _getFile();
final value = json.encode(data);
await file.writeAsString(value);
}
}

30
packages/shared_preferences/shared_preferences_aurora/pubspec.yaml

@ -0,0 +1,30 @@
name: shared_preferences_aurora
description: The Aurora OS implementation of shared_preferences.
version: 0.0.1
homepage:
environment:
sdk: '>=2.18.6 <3.0.0'
flutter: ">=2.5.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.0.2
shared_preferences: ^2.1.1
shared_preferences_platform_interface: ^2.2.0
path: ^1.8.2
path_provider: ^2.0.14
path_provider_aurora:
path: ../../path_provider/path_provider_aurora
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
plugin:
platforms:
aurora:
dartPluginClass: SharedPreferencesAurora
Loading…
Cancel
Save