Thursday, March 7, 2024

GetX (Reactive State Management) with GetxController (Controller)

 GetX (Reactive State Management) with GetxController (Controller)


  • With controller instance
  • With Get.find()


1. Create Controller

import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

class SimpleManagementController extends GetxController{
var count =0.obs;

void increment(){
count++;
}
}


2. Calling GetX

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx/controller/simplestatemanagement_controller.dart';

class SimpleStateManagementPage extends StatelessWidget {
SimpleStateManagementPage({super.key});
// Create object or instance
final SimpleManagementController controller=Get.put(SimpleManagementController());

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Get Builder"),
backgroundColor: Colors.greenAccent,
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Text("Welcome"),
              GetX<SimpleManagementController>(
builder: (_)=>Text("Clicks ${controller.count}")
),
],
),
),
),
floatingActionButton:
FloatingActionButton(
child:
Icon(Icons.add),
onPressed: (){
controller.increment();
},
),
);
}
}

3.Calling GetX Without instance of Controller Helping (Get.find)


import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx/controller/simplestatemanagement_controller.dart';

class SimpleStateManagementPage extends StatelessWidget {
SimpleStateManagementPage({
super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar:
AppBar(
title:
Text("Get Builder"),
backgroundColor: Colors.
greenAccent,
),
body:
SafeArea(
child:
SingleChildScrollView(
child:
Column(
children: [
Text("Welcome"),
              GetX<SimpleManagementController>(
init: SimpleManagementController(),
builder: (controller) => Text("Clicks ${controller.count}")),
],
),
),
),
floatingActionButton:
FloatingActionButton(
child:
Icon(Icons.add),
onPressed: () {
var controller=Get.find<SimpleManagementController>();
controller.increment();
},
),
);
}
}


No comments:

Post a Comment

Featured post

Compress Image With Show File Size & Resolution in Flutter

 Compress Image With Show File Size & Resolution  1.Multiple File Image Compress with file Size import 'dart:io' ; import 'p...

LightBlog