Understanding the GetX for State Management with the code to fetch data

GetX is a reactive and minimalist Flutter library for managing state, navigation, and dependencies. It provides a simple and efficient way to manage your application's state and make your code more organized and readable. With GetX, you can easily manage your app's state and access it from any widget in your app, without the need for scaffold-level providers, setState(), streams, or other complex state management patterns. This makes it a great choice for small to medium-sized Flutter apps that need a simple and lightweight solution for managing state.


File Name: product.dart

This is a class definition in Dart programming language, named Product. The class has 5 fields: id, productName, productImage, productDescription, and price. All fields are marked as final, meaning they are read-only and cannot be changed after the object is created.

The constructor of the class takes 5 named parameters, each of which corresponds to one of the class fields, and all parameters are marked as required, indicating that they must be provided when creating an object of this class. The constructor initializes the object's fields with the values passed as arguments.

The Product class can be used to create objects that represent products, with each object having a unique id, a productName, a productImage URL, a productDescription, and a price.

class Product {
  final int id;
  final String productName;
  final String productImage;
  final String productDescription;
  final double price;
    required this.id,
    required this.productName,
    required this.productImage,
    required this.productDescription,
    required this.price,

File Name: shopping_controller.dart

This is a Dart code that defines a class named ShoppingController that extends GetxController. GetxController is a base class from the Get library, a state management solution for Dart and Flutter.

The ShoppingController class has a field named products of type List<Product> that is marked as observable using obs from the Get library. This allows the controller to notify any interested parties when the value of products changes.

The class has a constructor marked with @override onInit, which is a method that gets called automatically when the controller is created. This method calls the super.onInit to ensure the base class's onInit is called and then calls fetchProducts to fetch the list of products.

The fetchProducts method is an asynchronous method that returns a Future that completes after 1 second. It defines a list of Product objects, adds it to the products field and sets its value to the list of Product objects.

The ShoppingController can be used to manage a list of products in a shopping application, allowing you to fetch products and notify any interested parties when the list of products changes.

import 'package:get/get.dart';

import '../model/product.dart';

class ShoppingController extends GetxController {
  var products = <Product>[].obs;

  void onInit() {

  void fetchProducts() async {
    await Future.delayed(Duration(seconds: 1));
    var productResult = [
          id: 1,
          price: 30,
          productDescription: 'some description about product',
          productName: '1st Prod'),
          id: 2,
          price: 40,
          productDescription: 'some description about product',
          productName: '2nd Prod'),
          id: 3,
          price: 49.5,
          productDescription: 'some description about product',
          productName: '3rd Prod'),
    products.value = productResult;

File Name: grid_view.dart

This is a Flutter widget that displays a product grid tile on a screen. The grid tile includes an image, a title and two buttons (favorite and shopping cart). The widget takes three parameters in its constructor:

  • id: The ID of the product
  • imageUrl: The URL of the product's image
  • title: The title of the product

The GridTile widget represents the overall structure of the grid tile and contains a GridTileBar widget as the footer, an image, and a GestureDetector widget as the child. The GridTileBar widget displays the title, leading and trailing icons. The leading icon is a favorite button and the trailing icon is a shopping cart button. The GestureDetector widget is used to detect gestures on the child, which is the product image. The Image.network widget displays the product image by loading it from the specified URL.

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../controller/shopping_controller.dart';

class GridViewOverView extends StatelessWidget {
  final int id;
  final String imageUrl;
  final String title;

  const GridViewOverView(
      {required this.id, required this.imageUrl, required this.title});

  Widget build(BuildContext context) {
    return GridTile(
      footer: GridTileBar(
        backgroundColor: Colors.black87,
        leading: IconButton(
          icon: Icon(Icons.favorite),
          onPressed: () {},
        title: Text(title),
        trailing: IconButton(
          icon: Icon(Icons.shopping_cart),
          onPressed: () {},
      child: GestureDetector(
        child: Image.network(
          fit: BoxFit.cover,

File Name: product_overview.dart

This is a Flutter widget, named ProductOverview, which is a StatelessWidget. It contains an AppBar widget at the top with a title "Products Demo", and the body of the screen contains a GridView widget that is built using the GetX package.

The GetX package is used to bind the ShoppingController to the ProductOverview widget, allowing the ShoppingController to manage the state of the products in the grid view.

The GridView uses SliverGridDelegateWithFixedCrossAxisCount as the gridDelegate with crossAxisCount set to 2, which means that there will be two columns in the grid view. The mainAxisSpacing and crossAxisSpacing are both set to 10, providing a margin of 10 pixels between the widgets in the grid view. The childAspectRatio is set to 1:1, meaning the aspect ratio of each child widget will be equal.

The itemCount is set to the length of the products array in the ShoppingController, which is updated by the controller based on the available products. The itemBuilder function takes the context and the index of the item being built, and returns a GridViewOverView widget for each product. The GridViewOverView widget takes the id, imageUrl, and title of each product as arguments, and displays the product in a grid tile.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/shopping_controller.dart';
import 'widgets/grid_view.dart';

class ProductOverview extends StatelessWidget {
  final shoppingController = Get.put(ShoppingController());

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Products Demo')),
        body: GetX<ShoppingController>(
          builder: (controller) {
            return GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 10,
                  crossAxisSpacing: 10,
                  childAspectRatio: 1 / 1),
              itemCount: controller.products.length,
              itemBuilder: (context, i) => GridViewOverView(
                id: controller.products[i].id,
                imageUrl: controller.products[i].productImage,
                title: controller.products[i].productName,

File Name: main.dart

The code defines a Flutter application with the main method main() that runs the application. main() calls the runApp() method and passes a MyApp widget.

MyApp is a StatelessWidget that returns a MaterialApp widget. MaterialApp sets up the base for the Flutter app, it takes various parameters such as title, theme, and home.

title sets the title of the application, theme sets the primary color of the application, and home sets the default page of the application.

In this code, the home parameter is set to ProductOverview, which is a class that extends the StatelessWidget and returns a Scaffold widget that contains an AppBar and a body. The body of the Scaffold widget is the GetX widget which returns the GridView.builder widget that shows a grid of products.

import 'package:flutter/material.dart';

import 'view/product_overview.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      home: ProductOverview(),

GitHub Links

Follow @PradeepTheDeveloper Star Issue Sponsor


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