Flutter: Need some help on approach for multiple Stateful Widgets in parent Widget with some degree of global accessibility

103

You can create StateNotifier/ChangeNotifier for maintaining the state and then wrap all your switches inside Consumer widgets.

Here is an example with ChangeNotifier: You can use a primitive type like an array or maybe a map for storing the state of switches.

class SwitchesNotifier extends ChangeNotifier {
 final switchesStateMap = <String, bool>{};

 void changeSwitchState(String switchKey, bool value) {
  if (switchesStateMap.containsKey(switchKey)) {
    switchesStateMap[switchKey] = value;
  } else {
    switchesStateMap[switchKey] = true;
  }
    notifyListeners();
  }
}

final switchesNotifierProvider = ChangeNotifierProvider((ref) => SwitchesNotifier());

Then you can wrap all your switches inside consumer widgets and to read the switch value based on your key and listen for state changes. Also don't forget to call changeSwitchState() inside onChanged callback of switch widget.

Consumer(
      builder: (_, ScopedReader watch, __) {
        final switchNotifier = watch(switchesNotifierProvider);
        final switchValue = switchNotifier.switchesStateMap['subtitles']
        ?? false;
        return Switch(
          value: switchValue,
          onChanged: (value) {
       context.read(switchesNotifierProvider).changeSwitchState('subtitles',value);
          }
        );
      },
    ),
Share:
103
emTeeDub
Author by

emTeeDub

Updated on December 22, 2022

Comments

  • emTeeDub
    emTeeDub over 1 year

    How would I go about maintaining the state of many individual material switches that represent the same information across the app? I have a rough representation of my pages and their widgets below.

    Account Page: I have a Form with 10 fields which have 10 concurrent switches for displaying/hiding the info submitted in the fields.

    Home Page: I have an expandable Personal Card that has 10 switches for quick display/hide of the same info from the Form.

    Any examples I find seem to just demonstrate managing a single widget's state. I've looked into Riverpod and like the ideas of it being 'global' and separate from the widget tree, to me this sounds like the most viable option. But not having used Riverpod, I am a bit confused with how to implement it with my case.

  • emTeeDub
    emTeeDub almost 3 years
    This makes sense. Thanks for your inputs, much appreciated!
  • Moksh Mahajan
    Moksh Mahajan almost 3 years
    Glad I cloud help :)