2

enter image description hereHi guys I am facing a problem which I have tried to solve through multiple approaches but failed. I have a stateful widget class which has a variable in its state I need to access the data in this variable from another stateful widget's class's state, I have tried accessing the variable by creating a GlobalKey for the class which contains the variable, but when I access the variable I get null. Am I accessing the variable the wrong, way or is there a more appropriate way of doing it?

1 Answers1

0

what i usually do in cases like this is i will define varableX globally so that i can access it from anywhere in my app. To do this install flutter_riverpod and define variableX like this:

final variableXProvider = StateProvider<bool>((ref)=> false/true);

inside your build method, you can access it like this

class StatefulWidget1 extends ConsumerStatefulWidget {
  const StatefulWidget1({Key? key}) : super(key: key);

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _StatefulWidget1State();
}

class _StatefulWidget1State extends ConsumerState<StatefulWidget1> {

  @override
  Widget build(BuildContext context) {
  //* watch variableX like this

    final varibleX = ref.watch(variableXProvider.state).state;

    return Scaffold(body: Column(
children: [
      Text(varibleX),

      //* to change the value of variableX you can do this

      ElevatedButton(onPressed: (){
        ref.read(variableXProvider.notifier).state = true/false;
      }, child: Text('Change value'))
    ],),);
  }
}

once you hit the button, the value changes without needing to call setState(). the ref object will automatically rebuild itself once it detects any changes.

john
  • 1,438
  • 8
  • 18