Dependency Injection in GetX
import "package:firebase/GetX/Controller.dart";
import "package:flutter/material.dart";
import "package:get/get.dart";
void main()
{
runApp(MyApp());
}
class MyApp extends StatelessWidget
{
MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: "Dependency Injection",
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: DependencyInjection(),
);
}
}
class DependencyInjection extends StatelessWidget
{
DependencyInjection({super.key});
/// My Controller instance will be created even if it is not used tag will be used
/// to find the instance with tag name Controller disposed when it is not used but if
/// permanent is true the instance will be alive throughout the app
// MyController myController = Get.put(MyController(), tag: "instance1", permanent: true);
@override
Widget build(BuildContext context) {
/// Instance will be created when it is used. "fenix" is similar to "permanent", the difference is that
/// the instance is discarded when is not being used, but when it's use is needed again,
/// Get will recreate the instance
// Get.lazyPut(() { return MyController(); }, tag: "instance2", fenix: true);
Get.putAsync<MyController>(() async { return await MyController(); },);
/// Here below, permanent will be true by default and isSingleton is false
// Get.create<MyController>(() { return MyController(); },);
return Scaffold(
appBar: AppBar(
title: const Text("Dependency Injection"),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
/// Instance will be created with tag
// Get.find<MyController>(tag: "instance1");
/// Find instance
Get.find<MyController>();
Get.find<MyController>().incrementCounter();
},
child: const Text("Click me!"),
),
],
),
),
);
}
}
import "package:get/get.dart";
import "package:shared_preferences/shared_preferences.dart";
class MyController extends GetxController
{
void incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt("counter") ?? 0) + 1;
print("Pressed $counter times");
await prefs.setInt("counter", counter);
}
}
Comments
Post a Comment