The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
相关问题
- suppress a singleton constructor in java with powe
- What means in Dart static type and why it differs
- Flutter : Prepare list data from http request
- How to schedule an alarm on specific time in Flutt
- MappedListIterable is not a SubType
相关文章
- Observatory server failed to start - Fails to crea
- Adding Shadows at the bottom of a container in flu
- Flutter. Check if a file exists before loading it
- How to fix a purported lack of an “explicit instan
- Receive share file intents with Flutter
- Do stateless widgets dispose on their own?
- Auto-property initializer Singleton implementation
- how to implement Alphabet scroll in flutter
Here is a simple answer:
What about just using a global variable within your library, like so?
single.dart
:main.dart
:Or is this frowned upon?
The singleton pattern is necessary in Java where the concept of globals doesn't exist, but it seems like you shouldn't need to go the long way around in Dart.
Here's a concise example that combines the other solutions. Accessing the singleton can be done by:
singleton
global variable that points to the instance.Singleton.instance
pattern.Note: You should implement only one of the three options so that code using the singleton is consistent.
If you need to do complex initialization, you'll just have to do so before using the instance later in the program.
Example
Hello what about something like this? Very simple implementation, Injector itself is singleton and also added classes into it. Of course can be extended very easily. If you are looking for something more sophisticated check this package: https://pub.dartlang.org/packages/flutter_simple_dependency_injection
After reading all the alternatives I came up with this, which reminds me a "classic singleton":
Here is a comparison of several different ways to create a singleton in Dart.
1. Factory constructor
2. Static field with getter
3. Static field
How to instanstiate
The above singletons are instantiated like this:
Note:
I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.