Last active
May 27, 2021 15:41
-
-
Save hotdang-ca/c5a37a74c6201abc0a1283f4bdff9080 to your computer and use it in GitHub Desktop.
Dart Singleton Example
This file contains 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/material.dart'; | |
class State with ChangeNotifier { | |
late num _count; | |
num get count => _count; | |
void setCount(newCount) { | |
_count = newCount; | |
notifyListeners(); | |
} | |
State._internal() { | |
_count = 0; | |
} | |
static final State _instance = State._internal(); | |
factory State() { | |
return _instance; | |
} | |
} | |
void main() { | |
print('Creating state...'); | |
State state = State(); | |
state.setCount(5); | |
print('Initial count: ${state.count}'); | |
print('Getting another instance...'); | |
State state2 = State(); | |
print('Singleton count: ${state2.count}'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment