flutter switch
flutter switch

Hi Guys, Welcome to Proto Coders Point. In this flutter article we will learn about flutter switch button & how to keep it on/off when user close the app, re-visit the app & switch button will be in same state as it was before user leave the app.

Note: To achieve this we will make use of 2 packages.

  1. Get: Also called as flutter GetX package, we will use it for Getx State Management in flutter.
  2. GetStorage: To store data of user action in app memory. GetStorage is alternative of SharedPreferences.

Video Tutorials on Flutter Switch with Getx

Flutter switch – using default state management – using setState()


Flutter switch button example – by using GetX State Management

Check out both the video to implement in your project while watching video.


Add dependencies get & getstorage

In your flutter project open pubspec.yaml then under dependencies add it.

dependencies:
  
  get: ^4.1.4
  get_storage: ^2.0.2

Get: Also called as GetX, used for many operation such as route management, state management, navigating pages, email validation, GetXStorage, show snackbar, show alert dialog and more.
In our project we will just use getx state management to update the widget state without refreshing complete widget tree just to update 1 widget.

GetStorage: A Flutter GetXStoarge is an alternative of sharedPreferences which help you to store app data in memery that a user perform.
In our project we will store weather the user has turned ON switch or OFF switch before leaving the app, and when he return to app the switch button in flutter will be in same state as it was before user leave the app.

Note: To use getstorage u must also add getX dependencies else getStorage will return you error.

Complete source code below

Flutter Switch example – using default setState() method to update UI & store switch on/off data using getStorage

main.dart

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final switchData = GetStorage();

   bool isSwitched = false;

  
   @override
  void initState() {
  
    super.initState();

    if(switchData.read('isSwitched') != null)
      {
        setState(() {
          isSwitched = switchData.read('isSwitched');
        });
      }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Switch(
                value: isSwitched, onChanged: (value)
               {
                  setState(() {
                        isSwitched = value;
                        switchData.write('isSwitched', isSwitched);
                  });
                }
            ),
          ],
        ),
      ) ,
    );
  }
}




Flutter Switch button Example using getx state management & store on/off data of switch using getstorage

Create new dart File by name ‘GetXSwitchState’ or any name as you want

[project] > lib (right click) > New > Dart File

GetXSwitchState.dart

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


class GetXSwitchState extends GetxController{
 
  // a variable to On Off Switch in flutter
  var isSwitcheded = false;
  
  // instance of GetStorage, to store data in key value pair.
  final switchdatacontroller = GetStorage();

  GetXSwitchState(){
    print("Constructor called");
    // when user re-visit app, we check previous state of app weather it was on or off.
    if(switchdatacontroller.read('getXIsSwitched') != null){
      isSwitcheded = switchdatacontroller.read('getXIsSwitched');
      update();
    }
  }
  // called when user click on switch to on/off it
  changeSwitchState(bool value){

    isSwitcheded = value;

     // store data in getstorage true or false 
     //here in key 'getXIsSwitched' we store bool type either true or else 
     // if true then switch is ON else OFF
    switchdatacontroller.write('getXIsSwitched', isSwitcheded);

    // update the UI
    update();
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_getx_storage/GetXSwitchState.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
     // Create a instance of GetXSwitchState class
   final GetXSwitchState getXSwitchState = Get.put(GetXSwitchState());
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(" Getx State Management Switch"),
            // we are wraping the switch with GetBuilder so that it keep observing any change need to be done
            GetBuilder<GetXSwitchState>(builder: (_) => Switch
              (value: getXSwitchState.isSwitcheded,
                onChanged: (value){
                   getXSwitchState.changeSwitchState(value);
                }))

          ],
        ),
      ) ,
    );
  }
}


In above code, we have create a instance object of GetXSwitchState, that will used to get data from it.
Then we are wraping the switch with GetBuilder so that it keep observing any change need to be done & update the UI as per user action.


Recommended Flutter Articles

Basic of Flutter GetX – Introduction to GetX Library

Flutter Dynamic theme change using GETX

Getx State Management