GetxController introduction

In the actual project development process, it is impossible for us to put UI code and business logic together, which will be fatal to the project architecture, code readability and later maintenance. Fortunately, GetX provides us with GetxController, GetxController main role is used for separating the UI code and business logic.

Video Tutorial Address

Zero basic video tutorial address

GetxController can be used in three ways

Here are three ways to get data dynamically using GetxController and how to update the data.

Step 1: Application entry setup

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerExample/GetXControllerExample.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX", home: GetXControllerExample(), ); }}Copy the code

Step 2: Define the controller inherits from GetxController

import 'package:flutter_getx_example/ObxCustomClassExample/Teacher.dart';
import 'package:get/get.dart';

class MyController extends GetxController {

  / / the first
  // var teacher = Teacher();
  //
  // void convertToUpperCase() {
  // teacher.name.value = teacher.name.value.toUpperCase();
  // }

  / / the second
  // var teacher = Teacher(name: "Jimi", age: 18).obs;
  // void convertToUpperCase() {
  // teacher.update((val) {
  // teacher.value.name = teacher.value.name.toString().toUpperCase();
  / /});
  // }

  / / the third kind
  var teacher = Teacher();

  voidconvertToUpperCase() { teacher.name.value = teacher.name.value.toUpperCase(); update(); }}Copy the code

Step 3: Instantiate the controller and use it


import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerExample/MyController.dart';
import 'package:get/get.dart';

class GetXControllerExample extends StatelessWidget {

  / / the first
  MyController myController = Get.put(MyController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GetX Obx---GetXController"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            / / the first
            // Obx(() => Text(
            / / "my name is ${myController. The teacher. The name}",
            // style: TextStyle(color: Colors.red, fontSize: 30),
            // )),
            / / the second
            // GetX<MyController>(
            // init: MyController(),
            // builder: (controller) {
            // return Text(
            ${controller.teacher.name};
            // style: TextStyle(color: Colors.green, fontSize: 30),
            / /);
            / /},
            // ),
            / / the third kind
            GetBuilder<MyController>(
              init: myController,
              builder: (controller) {
                return Text(
                  "My name is${controller.teacher.name}",
                  style: TextStyle(color: Colors.green, fontSize: 30)); }, ), SizedBox(height:20,),
            ElevatedButton(
              onPressed: () {
                / / the first
                myController.convertToUpperCase();

                / / the second
                // Get.find<MyController>().convertToUpperCase();

              },
              child: Text("Convert to uppercase"() [(), (), (); }}Copy the code

Results show

GetxController event listener

GetxController event listening, including listening to a single value, multiple values, etc.

Step 1: Application entry setup

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerWorkersExample/GetXControllerWorkersExample.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX", home: GetXControllerWorkersExample(), ); }}Copy the code

Step 2: Define the controller inherits from GetxController

import 'package:get/get.dart';

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

  voidincrement() { count++; }}Copy the code

Step 3: Rewrite onInit and listen for events

@override
void onInit() {
  // TODO: implement onInit

  // Listen for the value of count when it changes
  ever(count, (callback) => print("ever----$count"));

  // Listen for multiple values, called when they change
  everAll([count], (callback) => print("everAll----$count"));

  // called only once when the count value changes
  once(count, (callback) => print("once----$count"));

  // It is called 1 second after the user stops typing, mainly for anti-ddos
  debounce(count, (callback) => print("debounce----$count"));

  // Ignore all changes for 3 seconds
  interval(count, (callback) => print("interval----$count"));

  super.onInit();
}
Copy the code

Step 4: Instantiate the controller and use it


import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerWorkersExample/WorkersConroller.dart';
import 'package:get/get.dart';

class GetXControllerWorkersExample extends StatelessWidget {

  WorkersController workersController = Get.put(WorkersController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GetXWorkersController"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: () => workersController.increment(),
                child: Text("Add")
            ),
            Padding(
              padding: EdgeInsets.all(16), child: TextField( onChanged: (val) { workersController.increment(); }, ()], (), (), (); }}Copy the code

Results show

Console output

flutter: ever---- 1
flutter: everAll---- 1
flutter: once---- 1
[GETX] Worker [once] called
flutter: debounce---- 1
flutter: interval---- 1
flutter: ever---2 -
flutter: everAll---2 -
flutter: debounce---2 -
flutter: interval---2 -
flutter: ever---- 3
flutter: everAll---- 3
flutter: ever---4 -
flutter: everAll---4 -
flutter: ever---- 5
flutter: everAll---- 5
flutter: interval---- 5
flutter: debounce---- 5
Copy the code

GetxController life cycle

The life cycle of GetxController is explained here, including initialization, loading completion, destruction, etc.

Step 1: Application entry setup

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerLifecycleMethodsExample/GetXControllerLifecycleMethodExample.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX", home: GetXControllerLifecycleMethodExample(), ); }}Copy the code

Step 2: Define the controller inherits from GetxController

import 'package:get/get.dart';

class MyLifecycleController extends GetxController {

  var count = 0;

  void increment() async {
    await Future.delayed(Duration(milliseconds: 3000));
    count++;
    update();
  }

  void cleanTask() {
    print("Cleared the mission."); }}Copy the code

Step 3: Rewrite the GetxController lifecycle method

@override
void onInit() {
  // TODO: implement onInit
  print("Initialize");
  super.onInit();
}

@override
void onReady() {
  // TODO: implement onReady
  print("Load complete");
  super.onReady();
}

@override
void onClose() {
  // TODO: implement onClose
  print("Controller released");
  super.onClose();
}
Copy the code

Step 4: Instantiate the controller and use it


import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerLifecycleMethodsExample/MyLifecycleController.dart';
import 'package:get/get.dart';

class GetXControllerLifecycleMethodExample extends StatelessWidget {

  MyLifecycleController myLifecycleController = Get.put(MyLifecycleController());

  @override
  Widget build(BuildContext context) {
    print("build");

    return Scaffold(
      appBar: AppBar(
        title: Text("GetXControllerLifecycleMethod"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GetBuilder<MyLifecycleController>(
              initState: (data) => myLifecycleController.increment(),
              dispose: (_) => myLifecycleController.cleanTask(),
              builder: (controller) {
                return Text(
                  "The counter value is:${myLifecycleController.count}",
                  style: TextStyle(color: Colors.green, fontSize: 30)); },),],),),); }}Copy the code

Results show

Console output

Flutter: Initializes [GETX] Instance"MyLifecycleController" has been created
[GETX] Instance "MyLifecycleController" has been initialized
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController"The load of a flutter has been initialized. The flutter has been builtCopy the code

GetxController UniqueID

During development, we will encounter situations where multiple places reference the same attribute, but I only want to update a single place, so I can use the UniqueID to differentiate.

Step 1: Application entry setup

import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerUniqueIDExample/GetXControllerUniqueIDExample.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "GetX", home: GetXControllerUniqueIDExample(), ); }}Copy the code

Step 2: Define that the controller inherits from GetxController and define the uniqueID

import 'package:get/get.dart';

class CountController extends GetxController {
  var count = 0;

  void increment() {
    count++;
    update(['jimi_count']); }}Copy the code

Step 3: Instantiate the controller and use it


import 'package:flutter/material.dart';
import 'package:flutter_getx_example/GetXControllerUniqueIDExample/CountConroller.dart';
import 'package:get/get.dart';

class GetXControllerUniqueIDExample extends StatelessWidget {

  CountController countController = Get.put(CountController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GetX Obx---GetXController"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GetBuilder<CountController>(
              builder: (controller) {
                return Text(
                  "The counter value is:${controller.count}",
                  style: TextStyle(color: Colors.red, fontSize: 30)); }, ), GetBuilder<CountController>( id:'jimi_count',
              builder: (controller) {
                return Text(
                  "The counter value is:${controller.count}",
                  style: TextStyle(color: Colors.green, fontSize: 30)); }, ), SizedBox(height:20,),
            ElevatedButton(
              onPressed: () => countController.increment(),
              child: Text("Add"() [(), (), (); }}Copy the code

Results show

conclusion

This chapter explains the data assignment, data update, event monitoring, life cycle and UniqueID of GetxController, and also understands how to use GetxController to split the UI code and business logic of the project.