How to realize Flutter singleton
This article mainly explains "how to realize Flutter singleton". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve Flutter singleton"!
Singleton mode of Flutter (able)
In general, to use the singleton pattern in your code, there are the following established structural requirements:
The singleton class (Singleton) contains a static property instance (instance) that references its own class, and can create this instance on its own.
This instance can only be accessed through the static method getInstance ().
Class constructors typically have no arguments and are marked private, ensuring that the class cannot be instantiated from outside the class.
Reviewing iOS, the single example is written as follows:
Static JXWaitingView* shared;+ (JXWaitingView*) sharedInstance {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {shared= [[JXWaitingView alloc] initWithTitle:nil];}); return shared;}
The goal is to control that the initialization method is executed only once through dispatch_once, and then receives and returns it with a static-modified object. So the core is to perform initialization only once.
Create a singleton
Create a singleton case
Class Student {String? Name; int? Age; / / Construction method Student ({this.name, this.age}); / / singleton method static Student? _ dioInstance; static Student instanceSingleStudent () {if (_ dioInstance = = null) {_ dioInstance = Student ();} return _ dioInstancetesting;}} Test singleton effect Test-import 'package:flutter_async_programming/Student.dart';void main () {Student studentA = Student.instanceSingleStudent (); studentA.name = "Zhang San" Student studentB = Student.instanceSingleStudent (); print ('studentA name is ${studentA.name}'); print ('studentB name is ${studentB.name}');}
Running effect
Test 2: import 'package:flutter_async_programming/Student.dart';void main () {Student studentA = Student.instanceSingleStudent (); studentA.name = "Zhang San"; Student studentB = Student.instanceSingleStudent (); studentB.name = "Li Si"; print (' studentA name is ${studentA.name}'); print ('studentB name is ${studentB.name}');}
Running effect
At this point, I believe you have a deeper understanding of "how to achieve Flutter singleton". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!