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.


getx-to-fetch-data


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;
  Product({
    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;

  @override
  void onInit() {
    super.onInit();
    fetchProducts();
  }

  void fetchProducts() async {
    await Future.delayed(Duration(seconds: 1));
    var productResult = [
      Product(
          id: 1,
          price: 30,
          productDescription: 'some description about product',
          productImage:
              'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiArR9K9VJCNzFBtVQ_EWpVDkI3mQCYdNyXMkhz7ey-fZ94RxoKXh2FVm5qxpo0jiRz83UY-PrCovuiqpZKzwfHnJEZ7t9lX2Mdgpyq_rbo2XWUqmmG1iJU6-_a2O8xJBnQwbvRGOGKrvTzjtXpMQ13MqZPHh3K9fjfWM8eB1r7XyfWQU8LvHQhheT0hQ/w256-h256-p-k-no-nu/Container%20(2).png',
          productName: '1st Prod'),
      Product(
          id: 2,
          price: 40,
          productDescription: 'some description about product',
          productImage:
              'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTe3u20vdL_c3oks66u3WZMyhC5DrWNdPelfY944-evBM0FTscnrWC47ktwEv4mtA7S_QuEW9oFsuzd8JNIdVeKnYFLt2d-msjRa-I9Jl93yRBXDRz2MCL_avXCow688V00SbPiYTJY-oMxJsgbHuMzVv5J4TDBdIbxPNTj_BMvbuy5ICAdX-JCjSncg/w256-h256-p-k-no-nu/Container.png',
          productName: '2nd Prod'),
      Product(
          id: 3,
          price: 49.5,
          productDescription: 'some description about product',
          productImage:
              'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiK2RKPjW-AnaRJmzJtLNT2rTvdv-DGNfA0wVlNEzmz8xi6_zb-KyZP4H_uFvqMsuBBhaAqpph0lKgYNmKRs2VCM8AfxFZRr2Qqi950YOmZ4rwUi0ib9MJDo--u5Znaa339J2el_1LCwaxZqtlgeHd_ZVyI_EeLfmARx-lVdO4yUL9gNHi3KnBNNin_1A/w256-h256-p-k-no-nu/Restaurant%20App%20-%20Checkout_page%20(1).png',
          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});

  @override
  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(
          imageUrl,
          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());

  @override
  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});

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


GitHub Links

Follow @PradeepTheDeveloper Star Issue Sponsor

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

Understanding API integration with Getx State management

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