{"id":61829,"date":"2024-05-24T15:17:10","date_gmt":"2024-05-24T09:47:10","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=61829"},"modified":"2024-05-24T15:29:05","modified_gmt":"2024-05-24T09:59:05","slug":"getting-started-with-flutter-getx-state-management","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/getting-started-with-flutter-getx-state-management\/","title":{"rendered":"Getting started with Flutter GetX \u2013 State Management"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>When starting a new Flutter application, choosing the right state management approach is crucial. This blog aims to simplify that decision for you. In this tutorial on Flutter state management with GetX, I will introduce you to GetX, a robust Flutter framework.<\/p>\n<h2>GetX<\/h2>\n<p>State management facilitates data transfer within an application, triggering state updates and rebuilding the interface accordingly. This process is particularly critical in complex applications, where inefficient state updates can become costly. Flutter offers Stateful Widgets for managing state, but they come with certain limitations and are expensive to manage in terms of resource, performance and memory consumption.<\/p>\n<p>To address these limitations, we can use GetX for state management in Flutter. GetX is a robust and lightweight solution that also offers the below solutions:<\/p>\n<p>&#8211; State management<br \/>\n&#8211; Dependency injection<br \/>\n&#8211; Route management<\/p>\n<p><strong>Why GetX<\/strong><\/p>\n<div class=\"flex flex-grow flex-col max-w-full\">\n<div class=\"min-h-[20px] text-message flex flex-col items-start whitespace-pre-wrap break-words [.text-message+&amp;]:mt-5 juice:w-full juice:items-end overflow-x-auto gap-2\" dir=\"auto\" data-message-author-role=\"assistant\" data-message-id=\"895ecc23-73ac-4ec6-8916-fc65c97f7c06\">\n<div class=\"flex w-full flex-col gap-1 juice:empty:hidden juice:first:pt-[3px]\">\n<div class=\"markdown prose w-full break-words dark:prose-invert light\">\n<p>Let\u2019s explore why GetX is essential for state management in Flutter apps. GetX enhances Flutter applications in three key areas:<\/p>\n<ol>\n<li><strong>Performance<\/strong>: GetX optimizes resource consumption to enhance application performance. It avoids using ChangeNotifier or Streams, focusing instead on more efficient alternatives.<\/li>\n<li><strong>Organization and Readability<\/strong>: GetX separates the view from the business logic, offering a clear and simple syntax that improves the readability and organization of the code.<\/li>\n<li><strong>Productivity<\/strong>: With GetX&#8217;s straightforward syntax, developers can easily implement state management, even with complex code. This simplicity reduces development time and boosts productivity, ensuring maximum performance.<\/li>\n<\/ol>\n<h2>Installation<\/h2>\n<blockquote>\n<pre id=\"content_4_1\" class=\"lang-js s-code-block\"><strong><em>flutter pub add get\r\n<\/em><\/strong><\/pre>\n<\/blockquote>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h2>Counter App using Getx State Management<\/h2>\n<p>In this tutorial, I will be taking example of a counter app by separating the UI logic and business logic using a controller and the <strong>Obx<\/strong> widget step by step.<\/p>\n<pre id=\"content_5_5\" class=\"lang-js s-code-block\"><strong><em>class CounterRepository {\r\n  CounterRepository();\r\n<\/em><\/strong>\r\n<strong><em>  final Rx count = 0.obs;\r\n  final int _value = 1;\r\n\r\n  void increment() =&gt; count.value += _value;<\/em><\/strong>\r\n\r\n<strong><em>  void decrement() =&gt; count.value -= _value; \r\n}<\/em><\/strong><\/pre>\n<p>Get.lazyPut() allows you to initialise your controller when necessary, such as when your screen becomes visible to the user, and removes the controller when your screen is no longer part of the widget stack.<\/p>\n<pre id=\"content_5_21\" class=\"lang-js s-code-block\"><strong><em>void main() {<\/em><\/strong>\r\n<strong><em>  \/\/ Creating an instance of CounterRepository for dependency injection via Getx<\/em><\/strong>\r\n<strong><em>  Get.lazyPut(() =&gt; CounterRepository());\r\n  runApp(const MyApp());\r\n}\r\n\r\nclass MyApp extends StatelessWidget {\r\n  const MyApp({super.key});\r\n\r\n  @override\r\n  Widget build(BuildContext context) {\r\n    return GetMaterialApp(\r\n      title: 'Getx Demo',\r\n      theme: ThemeData(\r\n        primarySwatch: Colors.blue,\r\n      ),\r\n      home: const CounterScreen(),\r\n    );\r\n  }\r\n}\r\n<\/em><\/strong><\/pre>\n<p>Creating a Counter screen containing a number text, a button to navigate to another screen and a floating button to control the increment behaviour. The text widget is wrapped within Obx, enabling it to retrieve the value of the observable variable. Without Obx, the value would remain unchanged. The increment value is initialised in the controller as 0 which will be the initial value displayed at the run time.<\/p>\n<pre id=\"content_5_17\" class=\"lang-js s-code-block\"><strong><em>class CounterScreen extends StatelessWidget {\r\n  const CounterScreen({Key? key}) : super(key: key);\r\n\r\n  @override\r\n  Widget build(BuildContext context) {\r\n    final CounterRepository repo = Get.find();\r\n\r\n    return Scaffold(\r\n      appBar: AppBar(\r\n        title: const Text('Counter'),\r\n      ),\r\n      body: Center(\r\n        child: Column(\r\n          mainAxisAlignment: MainAxisAlignment.center,\r\n          children: [\r\n            ElevatedButton(\r\n              onPressed: () =&gt; {Get.to(() =&gt;SecondScreen())},\r\n              child: const Text('Open New page'),\r\n            ),\r\n            const SizedBox(height: 16),\r\n            Obx(\r\n              () =&gt; Text(\r\n                '${repo.count.value}',\r\n                style: Theme.of(context).textTheme.headlineMedium,\r\n              ),\r\n            ),\r\n          ],\r\n        ),\r\n      ),\r\n      floatingActionButton: FloatingActionButton(\r\n        onPressed:repo.increment,\r\n        child: const Icon(Icons.add),\r\n      ),\r\n    );\r\n  }\r\n}<\/em><\/strong><\/pre>\n<p>The second screen is navigated when we click the button using Getx&#8217;s Route management function <strong><em>Get.to\u00a0<\/em><\/strong>this function works similar to <em><strong>Navigator.of <\/strong><\/em>but without having to use context. Here also The text widget is wrapped within Obx which allows it to listen to changes and update accordingly. Since we are using the same object of <em><strong>CounterRepo\u00a0<\/strong><\/em>by getting it from getx dependency management the increment data will be preserved in the SecondScreen as well. We can use decrement function to make changes in the actual value using the instance of CounterController provided by Getx using <em><strong>Get.find()<\/strong><\/em>.<\/p>\n<pre id=\"content_5_17\" class=\"lang-js s-code-block\"><em><strong>class SecondScreen extends StatelessWidget {\r\n  const SecondScreen({Key? key}) : super(key: key);\r\n\r\n  @override\r\n  Widget build(BuildContext context) {\r\n    final CounterRepository repo = Get.find();\r\n\r\n    return Scaffold(\r\n      appBar: AppBar(\r\n        title: const Text('Counter'),\r\n      ),\r\n      body: Center(\r\n        child: Column(\r\n          mainAxisAlignment: MainAxisAlignment.center,\r\n          children: [\r\n            ElevatedButton(\r\n              onPressed: () =&gt; {Get.back()},\r\n              child: const Text('Go to previous Screen'),\r\n            ),\r\n            const SizedBox(height: 16),\r\n            Obx(\r\n              () =&gt; Text(\r\n                '${repo.count.value}',\r\n                style: Theme.of(context).textTheme.headlineMedium,\r\n              ),\r\n            ),\r\n          ],\r\n        ),\r\n      ),\r\n      floatingActionButton: FloatingActionButton(\r\n        onPressed:repo.decrement,\r\n        child: const Icon(Icons.remove),\r\n      ),\r\n    );\r\n  }\r\n}<\/strong><\/em><\/pre>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"size-large wp-image-61826\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2024\/05\/Untitled-design-1024x576.gif\" alt=\"screenshot\" width=\"625\" height=\"352\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2024\/05\/Untitled-design-1024x576.gif 1024w, \/blog\/wp-ttn-blog\/uploads\/2024\/05\/Untitled-design-300x169.gif 300w, \/blog\/wp-ttn-blog\/uploads\/2024\/05\/Untitled-design-768x432.gif 768w, \/blog\/wp-ttn-blog\/uploads\/2024\/05\/Untitled-design-624x351.gif 624w\" sizes=\"(max-width: 625px) 100vw, 625px\" \/><\/p>\n<p class=\"p1\"><b>Key Features:<\/b><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul class=\"ul1\">\n<li class=\"li1\"><b>Reactive Variables (Rx):<\/b>\u00a0Easily transform variables into observables using\u00a0.obs.<\/li>\n<li class=\"li1\"><b>Obx Widget:<\/b>\u00a0Reactive UI updates with minimal code.<\/li>\n<li class=\"li1\"><b>Workers:<\/b>\u00a0Manage asynchronous tasks, including debouncing, intervals, and one-time events.<\/li>\n<li class=\"li1\"><b>Simple State Manager (GetBuilder):<\/b>\u00a0Lightweight solution for managing multiple state updates efficiently.<\/li>\n<li class=\"li1\"><b>StateMixin:<\/b>\u00a0A streamlined approach to managing state with different statuses (loading, success, error).<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<p class=\"p1\"><b>Differences between builders:<\/b><\/p>\n<ul class=\"ul1\">\n<li class=\"li1\"><b>GetX vs GetBuilder:<\/b>\u00a0GetX utilizes reactive programming for finer-grained control, while GetBuilder offers a simpler, block-based approach.<\/li>\n<li class=\"li1\"><b>GetX vs Obx:<\/b>\u00a0GetX handles both reactive variables and mechanical updates, while Obx focuses solely on reactive changes.<\/li>\n<li class=\"li1\"><b>GetX vs MixinBuilder:<\/b>\u00a0MixinBuilder combines features of both GetX and GetBuilder, offering flexibility but with a higher resource consumption.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<ul>\n<li style=\"list-style-type: none;\">\n<p class=\"p1\"><b>Advantages:<\/b><\/p>\n<ul class=\"ul1\">\n<li class=\"li1\"><b>High Performance:<\/b>\u00a0Smart algorithms and optimizations minimize rebuilds and ensure efficiency.<\/li>\n<li class=\"li1\"><b>Granular Control:<\/b>\u00a0Precisely target which widgets are updated, avoiding unnecessary rebuilds.<\/li>\n<li class=\"li1\"><b>Easy to Learn:<\/b>\u00a0Intuitive syntax and clear concepts make state management accessible.<\/li>\n<li class=\"li1\"><b>Lightweight:<\/b>\u00a0Low memory footprint and minimal dependencies.<\/li>\n<li class=\"li1\"><b>Comprehensive Solution:<\/b>\u00a0Handles state management, navigation, and dependency injection.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2>Resources<\/h2>\n<ul>\n<li>Official Documentation can be found here &#8211; <strong><a href=\"https:\/\/github.com\/jonataslaw\/getx\/blob\/master\/documentation\/en_US\/state_management.md\">Link<\/a><\/strong><\/li>\n<li>Full source code here &#8211;<strong><a href=\"https:\/\/github.com\/divyanshuk10\/getx_test_app\"> Link<\/a><\/strong><\/li>\n<li>Getx pub can be found here &#8211; <strong><a href=\"https:\/\/pub.dev\/packages\/get\">Link<\/a><\/strong><\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>In conclusion, GetX stands as a versatile and powerful library within the Flutter ecosystem, offering streamlined solutions for state management, dependency injection, and route management. Its intuitive syntax, efficient performance, and robust capabilities make it a preferred choice for developers seeking to enhance their Flutter applications. With GetX, developers can achieve increased productivity, improved code organization, and optimized performance. As Flutter continues to evolve, GetX remains a valuable asset, empowering developers to create seamless and responsive applications across a variety of platforms. Whether you&#8217;re a seasoned developer or new to Flutter, exploring the features and functionalities of GetX can unlock a world of possibilities for your app development journey.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction When starting a new Flutter application, choosing the right state management approach is crucial. This blog aims to simplify that decision for you. In this tutorial on Flutter state management with GetX, I will introduce you to GetX, a robust Flutter framework. GetX State management facilitates data transfer within an application, triggering state updates [&hellip;]<\/p>\n","protected":false},"author":1598,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":109},"categories":[518],"tags":[4845,4968,5928,4848,5927],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61829"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1598"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=61829"}],"version-history":[{"count":3,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61829\/revisions"}],"predecessor-version":[{"id":61951,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61829\/revisions\/61951"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=61829"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=61829"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=61829"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}