Skip to content

Instantly share code, notes, and snippets.

@SabarishChungath
Created January 30, 2022 14:19
Show Gist options
  • Save SabarishChungath/a14c3812711e2d3286b4692531613b11 to your computer and use it in GitHub Desktop.
Save SabarishChungath/a14c3812711e2d3286b4692531613b11 to your computer and use it in GitHub Desktop.
Brief on Singletons and Mixins in dart/flutter
//Run this code snippet in dartPad
void main() {
// Example of creating Singletons in dart & Use of mixins.
// Singleton creates only one instance/object.
// Hence less memory allocation.
//Below we have created two instances but its initialised only once.
ApiService service1 = ApiService.instance;
ApiService service2 = ApiService.instance;
service1.fetchCart();
service2.callAllMethods();
service1.logout();
}
class ApiService with CartApiService, AuthApiService {
// We will be assigning a instance of this class within the class itself
// We use a private constructor for this [_privateConstructor]
// Note: Use _ in dart to make something private in dart;
static ApiService? _instance;
late String name;
// late Dio dio;
ApiService._privateConstructor() {
// Initialise everything here
// Usually in Api Service we initialise the network client here.
// dio = Dio.instance
name = "Hello Lokam!";
print("constructor initialised for one time only");
}
// static getter which returns the _instance;
static ApiService get instance {
if (_instance == null) {
// Null then ->
// initilise a instance by calling the private constructor
_instance = ApiService._privateConstructor();
return _instance!;
}
// Not Null ->
// Return the already created instance;
return _instance!;
}
void callAllMethods() {
print("\n\n==================>");
signUp();
login();
fetchCart();
addToCart();
deleteFromCart();
print("<===================\n\n");
}
}
// In Dart we can only inherit from a single class i.e only one super class
// But lets say you want multiple hierarchies
// Like in this example ApiService inherits from both AuthApiService and CartApiService
mixin AuthApiService {
signUp() {
print("Successfully Registered!");
}
logout() {
print("Logged out! Login to continue");
}
login() {
print("Successfully logged in");
}
}
mixin CartApiService {
fetchCart() {
print("Fetching products in cart");
}
addToCart() {
print("Adding item to cart");
}
deleteFromCart() {
print("Deleting item from cart");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment