Effortlessly Manage State in Flutter with GetX: A Complete Guide

This is a Flutter application written in Dart that uses the GetX package for state management. The main function creates and runs the MyApp widget, which is a MaterialApp that has a MyHomePage widget as its home screen. The MyHomePage widget is a stateless widget that uses GetBuilder to create an instance of MyHomePageController, a GetX controller that manages the state of the MyHomePage widget.


The MyHomePageController class extends GetXController and has a single observable variable, counter, which is initialized to 0. When the incrementCounter method is called, the value of counter is incremented by 1.

The MyHomePage widget's build method creates a Scaffold that has an AppBar, a Centered Column containing a Text widget and an Obx widget, and a FloatingActionButton. The Text widget displays a message, and the Obx widget displays the value of the counter variable from the MyHomePageController using the .value property. The FloatingActionButton has an onPressed callback that calls the incrementCounter method when pressed.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MyHomePageController>(
      init: MyHomePageController(),
      builder: (controller) => Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Obx(() => Text(
                    '${controller.counter.value}',
                    style: Theme.of(context).textTheme.headline6,
                  )),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => controller.incrementCounter(),
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

class MyHomePageController extends GetxController {
  var counter = 0.obs;

  void incrementCounter() {
    counter.value++;
  }
}

....

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management