Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Last active May 27, 2021 15:41
Show Gist options
  • Save hotdang-ca/c5a37a74c6201abc0a1283f4bdff9080 to your computer and use it in GitHub Desktop.
Save hotdang-ca/c5a37a74c6201abc0a1283f4bdff9080 to your computer and use it in GitHub Desktop.
Dart Singleton Example
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