Getx In Flutter

Getx In Flutter :

  • GetX is an extra-light,reactive state management,micro-framework and powerful solution for Flutter.
    • GetX provides a combination of State Management, Dependency Injection and Route Management solutions that work great together.
  • GetX does not use Streams or ChangeNotifier like other state managers. Why?

In addition to building applications for android, iOS, web, linux, macos and linux, with GetX you can build server applications with the same syntax as Flutter/GetX. In order to improve response time and reduce RAM consumption, we created GetValue and GetStream, which are low latency solutions that deliver a lot of performance, at a low operating cost. We use this base to build all of our resources, including state management.

  • Why choose (need)GetX state management pattern flutter?
  • Single GetX package provide the state management, dependency injection and route management. Common utility provide the GetX like validation, media query, no need to context navigation, change theme, change language, http etc. 
  • Less code writing use the GetX pattern.  For use controller access the variable or method only single line syntax.
  • Automatically clear resources.
  • Getx learn common doubt which component we should use, GetBuilder, GetX and Obx. put, find, memory, change language, change theme etc. out fluttertutotrial.in provides all doubt is clear the GetX related. 
  • GetX special
  • context

Flutter screen navigation not need to context in GetX.

Parent level context provide. For example: Anywhere context need to call the method Get.context().

  • High performance

GetX provide the one to keep in the memory as they are disposed automatically.

  • 100% Decoupling

Business logic is separated from UI, and even dependencies can be separated using something called Bindings.

  • Syntax

Easy to syntax GetX likes navigation, create the controller and UI refresh the data etc. For example you create the GetX controller extends GetxController.

  • Utility provide

Getx too is capable of running with the same code on Android, iOS, Web, Mac, Linux, Windows, and on your server

Navigation, Change the theme, change language, validation etc. For example Get.width, Get.height.

GetMaterialApp(
  enableLog: true,
logWriterCallback: localLogWriter, //custom log print
  defaultTransition: Transition.fade,
  opaqueRoute: Get.isOpaqueRouteDefault,
  popGesture: Get.isPopGestureEnable,
  transitionDuration: Get.defaultDurationTransition,
  defaultGlobalState: Get.defaultGlobalState,
);

void localLogWriter(String text, {bool isError = false}) {}

GetX is not a bloated. It has a multitude of features that allow you to start programming without worrying about anything, but each of these features are in separate containers, and are only started after use. If you only use State Management, only State Management will be compiled. If you only use routes, nothing from the state management will be compiled.

  • GetX in flutter reactive programming
  • You won’t need to create StreamControllers.
  • You won’t need to create a StreamBuilder for each variable
  • You will not need to create a class for each state.
  • You will not need to create a get for an initial value.
  • GetxController
  • Controllers are nothing your logic part put the new page, state changes, it is also where we will create our observables with their respective initial states and the events that will be responsible for changing those states.
  • Controller is nothing only class, controller contain the business logic. GetX automatically remove the resources from memory.
  • All the variables and methods are placed here and can be accessed from the view.
  • GetxController which extends DisposableInterfac that means controller will get deleted from memory as soon as the widgets using it are removed from the navigation stack.

GetX Controller access variable, method

final UserController userController = Get.put(UserController());
   or 
final userController = Get.put(UserController());

GetxController lifecycle:

  1. onInit(): Called immediately after the widget is allocated memory.
  2. onReady(): Called after widget is rendered on screen.
  3. onClose(): Called just before the controller is delete from memory.
  • GetX different way to listen or stream data
  • GetBuilder (onUpdate()): Less memory, fast as well. GetBuilder is called state. When update data method call onUpdate().
  • GetX (Stream builder): Reactive approx., continues listing state of variables.
  • Obx (Stream builder): reactive approx., continues listing data, code reduce.
  • Obx
  • Use:multiple controllers in the same widget or page.
Obx(() => Text(
  '${firstController.counter.value + thirtySeventhController.counter.value}'
  ))
  • Obx and Getx both streams auto update.
  • Reactive widget in GetX.
  • Just pass your Rx variable in the root scope of the callback to have itautomatically registered for changes.
final _name = "GetX".obs;
  • Local State Widgets

These Widgets allows you to manage a single value, and keep the state ephemeral and locally.For instance, you might use them to toggle obscureText in a TextField, maybe create a custom Expandable Panel, or maybe modify the current index in BottomNavigationBar while changing the content of the body in a Scaffold.

ObxValue local state widger:

Useful for simple local states, like toggles, visibility, themes,button states, etc.Reactive version.

ObxValue((data) => Switch(
         value: data.value,
       onChanged: (flag) => data.value = flag,
      ), false.obs)

  • ValueBuilder

A simplification of StatefulWidget that works with a .setState callback that takes the updated value.

ValueBuilder<bool>(
  initialValue: false,
  builder: (value, updateFn) => Switch(
    value: value,
    onChanged: updateFn, 
  ),
onUpdate: (value) =>print("Value updated: $value"),
  onDispose: () =>print("Widget unmounted"),
),
  • GetX update value using model class
//Model
   class User{
    String name; 
    User({this.name});
   }

   //UserController
   var user = User(name: 'Kamlesh').obs; 

   void changeName(){
     user.update((val){
       if(val.name  == 'kamlesh')
         val.name = 'Kamlesh flutter developer';
       else
         val.name = 'fluttertutorial.in world best free code provide';
     });
   } 

   //UI
final UserController userController = Get.put(UserController());

Obx(() => Text('${userController.user.value.name}'));  

   //call
userController.changeName();
  • Obs (RX Type)
  • obs is observable get or listing the update the data without refresh entries page.
  • RX Tpye: RxString, RxInt, RxMap, RxList, RxNum, RxDouble
  • GetX
  • Use: It redraws the widget only when the value of variable is actually changed.
  • GetBuilder is fast and has low memory.
  • GetX is very similar to GetBuilder in terms of syntax, but the approach is purely stream based.
  • If you don’t want to instantiate controllers.
GetX<Controller>(
  init: Controller(),
  builder: (val) => Text(
    '${val.counter.value}',
  ))
  • GetBuilder
  • Simple state manage.
  • Less memory, fast as well. GetBuilder is called state. When update data method call onUpdate().
//Controller code
  void increment(){
     count++; 
     update() //listing data
   }

  UI part
  GetBuilder<CountController>{
     init: CountController(), 
     builder: (value) => Text('${value.count}') 
  }

  Increment function call using GetBuider: 
Get.find<CountController>().increment();
  • Dependency injection () GetX in flutter:

Get has a simple and powerful dependency manager that allows you to retrieve the same class as your Bloc or Controller with just 1 lines of code, no Provider context, no inheritedWidget:

1) Get.lazyput (Not memory allocated): Memory is not allocated instance create but access the method allocated at that time memory.

  • Get.lazyput(fenix: true): Re-create instance.
  • mandatory: a method that will be executed when your class is called for the first time InstanceBuilderCallback builder.
  • optional: same as Get.put(), it is used for when you want multiple different instance of a same classmust be unique.
  • It is similar to ‘permanent’ the difference is that the instance is discarded when is not being use, but when it is use is needed again, Get will recreate the instance.
  • By default false.
  • Get.lazyput(fenix: true): Re-create instance.
  • mandatory: a method that will be executed when your class is called for the first time InstanceBuilderCallback builder.
  • optional: same as Get.put(), it is used for when you want multiple different instance of a same classmust be unique.
  • It is similar to ‘permanent’ the difference is that the instance is discarded when is not being use, but when it is use is needed again, Get will recreate the instance.
  • By default false.
Get.lazyPut<FirebaseAuth>(
  () => {
    return FirebaseAuth()
  },
  tag: Math.random().toString(),
  fenix: true
)

Get.lazyPut<ApiMock>(() => ApiMock());

2) Get.create:

  • Multiple instance create false.
    • Get.put and Get.lazyput ‘permanent’ true then create a single instance.
    • By default true.
    • Get.find() is called.

3) Get.put(tag: ‘any name, permanent: true):

  • By default permanent false:
  • Get has a simple and powerful dependency manager that allows you to retrieve the same class as your Bloc or Controller with just 1 lines of code, no Provider context, and no inheritedWidget.
  • When controller unused the automatically remove the memory permanent false, and we can use available throw out the app.
Get.find<Controller>(tag : 'tag Name');

5) Get.putAsync: If you want to register an asynchronous instance, you can use `Get.putAsync`:

Get.putAsync<Controller>(() async => await Controller());
Get.putAsync<SharedPreferences>(() async {
   final prefs = await SharedPreferences.getInstance();
   await prefs.setInt('counter', 12345);
   return prefs;
});
  • To remove an instance of Get flutter

Get.delete<Controller>(); usually you don’t need to do this because GetX already delete unused controllers.

  • Binding getx in flutter:
  • Use: Stream, timer.
  • Binding class will allow you to have SmartManager configuration control.
  • Bindings should be extended or implemented. When using GetMaterialApp, all GetPages and navigation methods (like Get.to()) have a [binding] property that takes an instance of Bindings to manage the dependencies() (via Get.put()) for the Route you are opening.
  • We write the business logic in controller after create instance of controller inside our UI after create instance we use variable and method controller. That is binding.
  • Implements Binding.
  • find: Get.find()create UI not instance create of controller.  
  • put: Not initialize controller error is get controller put.
  • Two types of binding getX in flutter:
  • Binding applied at route level
getPages: [ GetPage(name: '/home', page: () => Home(), binding: HomeControllerBinding())]

2) BindingBuilder: Not use separate binding class

getPages: [
GetPage(
name: '/home',
page: () => LoginPage(),
binding: BindingsBuilder(
() => {Get.lazyPut<LoginBinding>(() => LoginBinding())})), 
]  

   UI: Get.find<LoginController>().username;

  3) Normal Routes:Get.to(Home(), binding: HomeControllerBinding())

  • Smart management getX in flutter:
GetX provides smartmanagement that lets us configure:
GetMaterialApp{
	smartManagement: 
}

smartManagement options in getx, by default mode full.

1) SmartManagment.full

2) SmartManagment.keepFactory

3) SmartManagment.onlyBuilder

full:

  • Everything gets disposed as soon as the route is removed from navigation stack unless declared permanent.

keepFactory:

  • Just like full, it will remove its dependencies when it’s not being used anymore. However, it will keep their factory, which means it will recreate the dependency if you need that instance again.

only Builders:

  • With this option, only controllers statted in init or loaded into a Binding with Get.lazyput() will be disposed.
  • If you use Get.put or Get.putAsync or any other approach, smartmanagement will not have permissions to exclude this dependency.
  • GetView and GetWidget:

GetView

  • If we have single controller as a dependency then we can use GetView instead of StatelessWidget and avoid writing Get.find().
  • ALWAYS remember to pass the ` ControllerName` you used to register your controller.
  • for example: class MyApp extends GetView<ControllerName>
  • Access method: controller.username()

GetWidget :

  • GetWidget is a great way of quickly access your individual Controller.
  • It is similar to GetView with one difference it gives the same instance of Get.find() every time. It becomes very useful when used in combination with Get.create().
  • GetWidget is perfect to multiples instance of the same controller. EachGetWidget will have your own controller and will be call events as onInitand onClose when the controller get in/get out on memory.
  • Instance create: Get.create(() => CountController());
  • extend GetWidget: MyApp extends GetWidget<ControllerName>
  • Access method: controller.username();
  • GetView same instance create and GetWidget different instance create.
  • getx in flutter using GetService
  • Controller remove memory in onClose() method call. GetService alive the app is open. GetService same lifecycle controller likes onInit(), onReady(), onClose(). GetService remove memory app close.
  • For example: Session value store, Notification counter.
  • GetService and controller different only remove memory related.
  • Getx in flutter get_util

extensions

  1. context_extensions: isPhone, isSmallTablet , isLargeTablet , isTablet , showNavbar, textScaleFactor, mediaQueryShortestSide, isDarkMod, orientation(isPortrait, isLandscape), devicePixelRatio, iconColor
  2. double_extensions: toPrecision
  3. duration_extensions
  4. dynamic_extensions: isNull, isBlank, isNullOrBlank, printError, printInfo.
  5. event_loop_extensions
  6. internacionalization
  7. num_extensions: isLowerThan, isGreaterThan, isEqual, milliseconds, seconds, minutes, hours, days
  8. string_extensions: isNum, isNumericOnly, isAlphabetOnly, isBool, isVectorFileName, isImageFileName, isAudioFileName, isVideoFileName, isTxtFileName, isDocumentFileName, isExcelFileName, isPPTFileName, isAPKFileName, isPDFFileName,isHTMLFileName, isURL, isEmail, isPhoneNumber, isDateTime, isMD5, isSHA1, isSHA256, isBinary, isIPv4, isIPv6, isHexadecimal, isPalindrom, isPassport, isCurrency, isCpf, isCnpj, isCaseInsensitiveContains, isCaseInsensitiveContainsAny, capitalize, capitalizeFirst, removeAllWhitespace, camelCase, numericOnly
  9. widget_extensions: WidgetPaddingX, WidgetMarginX, WidgetSliverBoxX
  • get_navigation
  • bottomsheet
  • dialog
  • root: GetCupertinoApp, GetMaterialApp

Navigation screen methods getx

1)  Get.offNamed(): Current screen clear navigation history that is used to login or signup to home page.

2)  Get.back(): Back the screen.

3)  Get.toNamed(): New page navigation

4)  Get.offAllNamed(): Used to all pages clear history for example logout.

  • Getx snackbar (Toast)
  void toast(
      {String title = appName,
      message,
      Color backgroundColor = toastBackgroundColor,
      Color textColor = toastMessageColor,
      SnackPosition flushBarPosition = SnackPosition.BOTTOM}) {
    Get.showSnackbar(GetBar(
        animationDuration: Duration(seconds: 2),
        message: '',
        title: '',
        isDismissible: true,
        snackStyle: SnackStyle.FLOATING,
        backgroundColor: Colors.black.withOpacity(0.2),
        duration: Duration(milliseconds: 2000),
        overlayColor: Colors.black,
        overlayBlur: 0,
        backgroundGradient: LinearGradient(
            colors: [
              Colors.white,
              Colors.deepOrange.withOpacity(0.8),
            ],
            begin: const FractionalOffset(0.0, 0.0),
            end: const FractionalOffset(0.0, 2.0),
            stops: [0.0, 1.0],
            tileMode: TileMode.clamp),
        barBlur: 6,
        titleText: Text(title, style: flushBarTitleStyle(toastTitleColor)),
        messageText: Text(message, style: flushBarMessageStyle(textColor))));
  }
  • Getx in flutter animation GetX controller (rx_ticket_provider_mixin)
class SplashController extends GetxController with SingleGetTickerProviderMixin { }
void onInit() {
 }
  • FullLifeCycleController
class HomeController extends FullLifeCycleController with FullLifeCycle {
  // Mandatory
  @override
  void onDetached() {
    print('HomeController - onDetached called');
  }

  // Mandatory
  @override
  void onInactive() {
    print('HomeController - onInative called');
  }

  // Mandatory
  @override
  void onPaused() {
    print('HomeController - onPaused called');
  }

  // Mandatory
  @override
  void onResumed() {
    print('HomeController - onResumed called');
  }

  // Optional
  @override
  Future<bool> didPushRoute(String route) {
    print('HomeController - the route $route will be open');
    return super.didPushRoute(route);
  }

  // Optional
  @override
  Future<bool> didPopRoute() {
    print('HomeController - the current route will be closed');
    return super.didPopRoute();
  }

  // Optional
  @override
  void didChangeMetrics() {
    print('HomeController - the window size did change');
    super.didChangeMetrics();
  }

  // Optional
  @override
  void didChangePlatformBrightness() {
    print('HomeController - platform change ThemeMode');
    super.didChangePlatformBrightness();
  }
}

SuperController

@override
void onDetached() {}

@override
void onInactive() {}

@override
void onPaused() {}

@override
void onResumed() {}

StateMixin Getx

class HomeController extends GetxController with StateMixin<List<StateModel>> {
  
  @override
  void onInit() {
    super.onInit();
  
     change(data, status: RxStatus.success()); //Success
     change(null, status: RxStatus.error(err.toString())); //Error
     change(null, status: RxStatus.loading());
     
  }
}

Container(
        child: controller.obx(
          (state) => ListView.builder(
            itemCount: state.length,
            itemBuilder: (context, index) {
              return Container();
            },
          ),
          onLoading: Center(child: CircularProgressIndicator()),
          onError: Center(
            child: Text(
              'Erro ao consultar os Estados do Brasil',
              style: TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  • getX in flutter Stream
  • GetStream is the lightest and most performative way of working with events at Dart. You syntax is like StreamController, but it works with simple callbacks. In this way, every event calls only one function.
  • There is no buffering, to very low memory consumption.
  • Event add will add an object to stream. addError will add an error to stream. Listen is a very light StreamSubscription interface. Is possible take the last value with the value property.
class GetStream<T> {
  void Function() onListen;
  void Function() onPause;
  void Function() onResume;
  FutureOr<void> Function() onCancel;
}
  • Get connect
  • Get connect package use the API call, web socket call in a flutter.
  • Firestore GetX get the data stream using
FirebaseFirestore _firebaseFireStore;
FireStoreDatabaseProvider(this._firebaseFireStore);

Stream<List<NotificationCounterResponse>> fetchNotificationCounter() =>
_firebaseFireStore
.collection(tableNameNotificationCounter)
        .snapshots()
        .map((docs) =>docs.docChanges
.map<NotificationCounterResponse>((response) =>
NotificationCounterResponse.fromDocumentSnapshot(response))
            .toList());

Controller

var rxNotificationList = Rx<List<NotificationCounterResponse>>([]);

List<NotificationCounterResponse>get notificationList =>rxNotificationList.value;

@override
void onInit() {
super.onInit();
rxNotificationList.bindStream(fireStoreDatabaseRepository.notificationCounter());
}

Controller

  • fluttertutorial provide the best application using state management getx using.
  • Api call using getx in flutter.
  • Firebase retrieve or get the data using getx in flutter.
  • Search, delete, and update using getx in flutter.
  • Section or group by search using getx in flutter.
  • Live stream using getx in flutter.
  • Favorite using getx in flutter.
  • Preparation time change getx in flutter.
  • Bottom navigation bar getx in flutter.
  • Reactive syntax getx in flutter.
  • Clean architecture getx in flutter.
  • User profile edit getx in flutter.
  • GetX using every 1 min api call or notification get.

DATA PASS :

GET ARGUMENT: Get.arguments

PASS ARGUMENT: Get.offNamed(ROUTE_HOME, arguments: ‘KAMLESH’);

Step: 1 Add the pubspec.yaml

get :

Step: 2 MaterialAppreplace  theGetMaterialApp

classMyAppextends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
        title: '',
        theme: ThemeData(
primarySwatch: Colors.green,
fontFamily: quickFont,
visualDensity: VisualDensity.adaptivePlatformDensity),
        home: SplashPage(),
initialBinding: SplashBinding(),
getPages: AppPages.pages);
  }
}

Step: 3 Pages

class AppPages {
static final List<GetPage>pages = [
GetPage(name: ROUTE_SPLASH, page: () =>SplashPage(), binding: SplashBinding()),
GetPage(name: ROUTE_LOGIN, page: () =>LoginPage(), binding: LoginBinding()),
GetPage(name: ROUTE_HOME, page: () =>HomePage(), binding: HomeBinding()),
GetPage(name: ROUTE_ORDER, page: () =>OrderPage(), binding: OrderBinding()),
GetPage(name: ROUTE_FAVOURITE, page: () =>FavouritePage(), binding: FavouriteBinding()),
  ];
}

Step: 4 Controller

Controller extends GetxController.

Put the business logic.

All the method and variable accessed from the view.

Access controller: Controller controller = Get.put(Controller());

GetX provides a class called GetxController which extends DisposableInterface.

This means that our controller will get deleted from memory as soon as the widgets using it are removed from the navigation stack. We don’t have to manually dispose anything and the memory consumption is reduced, resulting in high performance.

GetxController comes with onInit() and onClose() methods which essentially replace the initState() and dispose() methods of the StatefulWidget.

This allows us to completely avoid using StatefulWidget and write highly organized code.

First time api call :
@override
void onInit() {
callFavourite('');
super.onInit();
}

Step: 5 Binding

classSplashBindingextends Bindings {
@override
void dependencies() {
Get.lazyPut(() =>SplashController());
  }
}

Step: 6 Model class using value notify

class OrderResponse {
  List<Order>orderList;

OrderResponse({this.orderList});
}

class Order {
  Order({bool isFavourite}) {
this.setFavourite(isFavourite);
  }

RxBoolisFavourite= RxBool(null);
setFavourite(bool value) =>isFavourite.value= value;
}

That is put the controller file

UPDATE GET USING FLUTTER USING FAVOURITE

voidisFavorite(Order order) {
order.setFavourite(order.isFavourite.value? false : true);
}

INDEX USING UPDATE GET IN FLUTTER

voidbySetFavourite(categoryId) {
categoryList
.firstWhere((prod) =>prod.categoryId== categoryId)
          .isFavourite
.value =
      !categoryList
.firstWhere((prod) =>prod.categoryId== categoryId)
          .isFavourite
.value;
}

REMOVE GET USING FLUTTER :

voidremoveOrder(String orderId) {
intindexGet =
orderList.indexWhere((element) =>element.orderId.value== orderId);
orderList.removeAt(indexGet);
}

DOWNLOAD SOURCE CODE :

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application