Search code examples
flutterflutter-getxflutter-state

Flutter toggle button using Getx for state management


I'm making a toggle button to switch between the unit system, I need to do it using Getx for state management.

This code works, but its using setState() instead

This is the (simplified) code:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_toggle_tab/flutter_toggle_tab.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({this.title});

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _tabTextIndexSelected = 0;
  final _listTextTabToggle = ["km / m", "m / ft"];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            children:[
              FlutterToggleTab(
                selectedIndex: _tabTextIndexSelected,
                selectedBackgroundColors: const [
                  Colors.blue,
                  Colors.blueAccent
                ],
                selectedTextStyle: const TextStyle(
                    color: Colors.white),
                unSelectedTextStyle: const TextStyle(),
                labels: _listTextTabToggle,
                selectedLabelIndex: (index) {
                  setState(() {
                    _tabTextIndexSelected = index;
                  });
                },
                isScroll: false,
              ),
              Text(
                "Index selected : $_tabTextIndexSelected",
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Tried to add obs to the variable _tabTextIndexSelected and obx to everything that is supposed to change, but it doesn't work.

Also, I'm using https://pub.dev/packages/flutter_toggle_tab

this is what I tried (two codes are from different files, I like to try first rather than doing it in my project):

RxInt _tabTextIndexSelected = 0.obs;
  final _listTextTabToggle = ["km / m", "m / ft"];
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
            body: Column(
              children: [
                Obx(
                    ()=> FlutterToggleTab(
                      selectedIndex: _tabTextIndexSelected,
                      selectedBackgroundColors: const [
                        Colors.blue,
                        Colors.blueAccent
                      ],
                      selectedTextStyle: const TextStyle(
                          color: Colors.white),
                      unSelectedTextStyle: const TextStyle(),
                      labels: _listTextTabToggle,
                      selectedLabelIndex: (index) {

                          _tabTextIndexSelected = index.obs;

                      },
                      isScroll: false,
                    ),
                ),
                Obx(
                    ()=>Text(
            "Index selected : $_tabTextIndexSelected",
          ),
                ),

Solution

  • The reactive variable and list of tabs string declaration inside the getx controller.

    Below is the working snippet to toggle the tabbar.

    import 'package:flutter/material.dart';
    import 'package:flutter_toggle_tab/flutter_toggle_tab.dart';
    
    import 'package:get/get.dart';
    
    class TestController extends GetxController {
      final listTextTabToggle = ["km / m", "m / ft"];
    
      RxInt tabTextIndexSelected = 0.obs;
    
      toggle(int index) => tabTextIndexSelected.value = index;
    }
    
    class TestPage extends StatelessWidget {
      const TestPage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        final ctrl = Get.put(TestController());
        return SafeArea(
          child: Scaffold(
              body: Column(children: [
            Obx(
              () => FlutterToggleTab(
                selectedIndex: ctrl.tabTextIndexSelected.value,
                selectedBackgroundColors: const [Colors.blue, Colors.blueAccent],
                selectedTextStyle: const TextStyle(color: Colors.white),
                unSelectedTextStyle: const TextStyle(),
                labels: ctrl.listTextTabToggle,
                selectedLabelIndex: (index) => ctrl.toggle(index),
                isScroll: false,
              ),
            ),
            Obx(
              () => Text(
                "Index selected : ${ctrl.tabTextIndexSelected.value}",
              ),
            )
          ])),
        );
      }
    }

    Output: enter image description here