Home > Blockchain >  How to Write this in Getx Controller
How to Write this in Getx Controller

Time:03-01

How to Write this in GetxController Class The Concept is I need to Select Item from Listview the selected item will be marked as tick if the item is selected my contine button will be enabled

var WidgetVisible = false;

setState(() {
widgetVisible = true;
selectedIndex = index;
});

CodePudding user response:

Step -1) First Create a Controller and Extend it from GetXController.
Step -2) Assign your dynamic values with ".obs". The .obs property will make your variables observable thus any changes will be automatically reflected without calling setState

import 'package:get/state_manager.dart';

class MyController extends GetxController {
  Rx<bool> widgetVisible = false.obs;
  Rx<int> selectedIndex = 0.obs;

  toggleVisibility(){
    widgetVisible.value = !widgetVisible.value;
  }

  setSelectedIndex(int index){
    selectedIndex.value = index;
  }
}

Now wrap your view with GeX<MyController> and access your variables with .value property

import 'package:your_project/some_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class HomeView extends StatelessWidget {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: GetX<MyController>(
        init: MyController(),
        builder: (controller) {
          return Column(
            children: [
              if (controller.widgetVisible.value) const Text("It is visible"),
              ElevatedButton(
                onPressed: () {
                  controller.toggleVisibility();
                },
                child: const Text("Toggle Visibility"),
              ),
            ],
          );
        },
      ),
    );
  }
}

CodePudding user response:

Need to understand properly the use of GetX here is example https://bartvwezel.nl/flutter/flutter-getx-example-category-selection/

=>How to use it in our flutter applications https://medium.com/mindful-engineering/lets-getx-in-flutter-4eaff2826ac7

CodePudding user response:

  1. prefer https://github.com/jonataslaw/getx for more details
import 'package:get/get.dart';

class Controller extends GetxController{
  var widgetVisible = false.obs;
  var selectedIndex = 0.obs;
  // use this fun in your  main page
  void test(int index){
    widgetVisible.value = true;
    selectedIndex.value = index;
  }
}
  • Related