Created
July 29, 2025 20:03
-
-
Save iapicca/1278861499dec86e8a10d03ebe77619f to your computer and use it in GitHub Desktop.
dart-pad_issues_3046
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/foundation.dart' show ValueListenable; | |
| import 'package:shared_preferences/shared_preferences.dart' | |
| show SharedPreferences; | |
| import 'package:flutter/material.dart'; | |
| void main() async { | |
| final counter = await SharedCounter.instance(); | |
| runApp( | |
| MaterialApp( | |
| home: Scaffold( | |
| body: Center( | |
| child: ValueListenableBuilder<int>( | |
| valueListenable: counter, | |
| builder: (context, count, _) => Text('$count'), | |
| ), | |
| ), | |
| floatingActionButton: FloatingActionButton( | |
| onPressed: () => counter.value++, | |
| tooltip: 'Increment', | |
| child: const Icon(Icons.add), | |
| ), | |
| ), | |
| ), | |
| ); | |
| } | |
| abstract class Counter extends ValueListenable<int> with ChangeNotifier { | |
| @override | |
| int get value; | |
| set value(int value); | |
| } | |
| final class SharedCounter extends Counter { | |
| SharedCounter._( | |
| this._prefs, | |
| String key, | |
| this.initialValue, | |
| ) : _key = key; | |
| final SharedPreferences _prefs; | |
| final String _key; | |
| final int initialValue; | |
| static Future<SharedCounter> instance({ | |
| String key = 'COUNTER', | |
| initialValue = 0, | |
| }) async => | |
| SharedCounter._( | |
| await SharedPreferences.getInstance(), | |
| key, | |
| initialValue, | |
| ); | |
| @override | |
| int get value => _prefs.getInt(_key) ?? initialValue; | |
| @override | |
| set value(int value) { | |
| _prefs.setInt(_key, value); | |
| notifyListeners(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment