Flutter GetX | Flutter State Management A Simple Shopping Cart

You will learn about Flutter GetX State Management using a simple shopping cart. 

If you want to learn about BLoC shopping cart go here.

You will build the ui and use getx package to manage our state across the app and learn adding two values. Flutter getx advantages are that, it's much simple and easy to use route and state management.

In this application, you cad add numbers and remove items from the shopping cart. It's more like a e-commerce.

So main featues of this simple app

1. creating obs type variable

2. adding items(a number) to the cart

3. removing items(a number) from the cart

4. total items( a sum of two numbers) 

GetxController

We created a class name MyController which extends GetxController.

Inside this class we declared reactive variable sname books and pens of obs type for our simple shopping cart.

var books = 0.obs
var pens  = 0.obs

The type obs makes your variable reactive. It would help to add or remove books from the cart.

We created method name increment() to call from UI..

On the onTap or onPressed event we will call increment() as our callback function and it would increase the value of books.

To increase the value of the shopping cart we just simple did

increment(){
  books.value++;
}

To decrease the shopping cart value we did

decrement(){
  books.value--;
}

We also used a Get.snackbar to show messages to user in case books.value-- become less than zero.

Similary we have methods to controller th pens value name incrementPens() and decrementPens().

 

Inject MyController

In our Ui, we wanna access the controller so that we can access the books varaible.

That's why we inject the controller in MyCart class. This is also called dependency injection.

MyController c = Get.put(MyController));

To be able to use the obs type variable in our Ui widget we need to use Obx() widget. It's a Getx widget which makes UI stateful.

Obx(()=>Text("${c.book.toString()}"))

The similar approach to acces number of pens has been used in the UI.

At the end we have added two items to show the total number

int get sum=>books.value + pens.value;

The variable sum returns the totall of books and pens. So it's more like adding two variable. 

Since books and pens are reactive or obs type sum automitically becomes reactive.

Actual shopping app

Recent posts