Update StatelessWidget UI dynamically using Get in Flutter


As we know StatefullWidget can update UI using setState ( ) method. When we made changes in the variable binded to a UI , changes can be made possible with SetState. How about StatelessWidget ?

Usually StatelessWidget redraw UI by the parent widget. Suppose you had a Cart page in which add new products to the shopping cart, which is a StatelessWidget. Need to update the count of items and bind to the UI, so it can dynamically update.

The Get Framework, Sate management tool, here to help and manage state of widget for you. Get has its own dependency /state management system so we need not feel the pain.

So how do we use Getx , add the dependency

Dependency

dependencies:
  flutter:
    sdk: flutter
  get:

Package import

import 'package:get/get.dart';

import the package into your module

Controller class

Controller class is key to state management, all methods and variables can be used with any part of your project. Extend a new class fromGetxController

class Controller extends GetxController {
  var tot = 0.obs;   
// update();
}do

The Controller class detect change UI using Update method. In other words we can make variables obervable with update or for react like programming use .obs at the end of assignment instead of using update();.

We also need to create a controller variable as follows in the widget

final controller = Get.put(Controller());

Using it in the UI

Now we are ready to use it in a widget using Obx( ) function as follows

Obx(
  () => Text(
    '${controller.tot}',
    style: TextStyle(fontSize: 25),
  ),

try to change the value of variable in a buttons click

IconButton(
  icon: Icon(
    Icons.add,
    size: 50,
    color: Colors.deepOrangeAccent,
  ),
  onPressed: () {
    controller.qty++;
  },
),

and it will update the UI.

You may also interested in these Get tutorials

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.