From b267459114e989fe9ec4d930704b614b5ce1212d Mon Sep 17 00:00:00 2001 From: Elias Projahn Date: Sun, 19 Jan 2020 12:57:16 +0100 Subject: [PATCH] Add coins to storage This adds an integer value representing the amount of coins that the player has. Therefore rxdart is introduced as a dependency. --- lib/storage.dart | 19 ++++++++++++++++++- pubspec.yaml | 1 + 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/storage.dart b/lib/storage.dart index 5b5947c..7b31147 100644 --- a/lib/storage.dart +++ b/lib/storage.dart @@ -1,8 +1,11 @@ +import 'package:rxdart/rxdart.dart'; import 'package:shared_preferences/shared_preferences.dart'; final storage = Storage(); class Storage { + final coins = BehaviorSubject.seeded(0); + SharedPreferences shPref; int get highScore1 { @@ -30,7 +33,21 @@ class Storage { } Future init() async { - shPref = await SharedPreferences.getInstance(); + if (shPref == null) { + shPref = await SharedPreferences.getInstance(); + + try { + coins.add(shPref.getInt('coins') ?? 0); + } on TypeError { + // Nothing to do + } + } + } + + Future addCoins(int amount) async { + final newCoins = coins.value + amount; + coins.add(newCoins); + await shPref.setInt('coins', newCoins); } Future addScore(int score) async { diff --git a/pubspec.yaml b/pubspec.yaml index 81de93a..61764e1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,6 +12,7 @@ dependencies: sdk: flutter flutter_localizations: sdk: flutter + rxdart: shared_preferences: sprintf: vector_math: