Home > Net >  Widget not updating flutter
Widget not updating flutter

Time:11-03

I'm trying to change the variable from another stateful class.

class first extends statefulwidget { 
    bool text = false;
    
    Widget build(BuildContext context) {
       setState((){});
       return Container(
           child: text ? Text('Hello') : Text('check')
       );
   } 
}

class second extends statefulwidget { 
   Widget build(BuildContext context) { 
       return Container( 
           child: IconButton( 
                 onPressed: () { 
                   first fir = first(); 
                   setState((){ 
                      fir.test = true; 
                   }); 
                } 
            ) 
       ); 
   } 
} 

widget shows only check not showing Hello

This is my code...Ignore spelling mistakes and camelcase

Give me the solutions if you know..

CodePudding user response:

try to reference to this answer, create function to set boolean in class1 and pass as parameter to class 2 and execute it :

typedef void MyCallback(int foo);

class MyClass {
  void doSomething(int i){

  }

  MyOtherClass myOtherClass = new MyOtherClass(doSomething);
}


class MyOtherClass {
  final MyCallback callback;

  MyOtherClass(this.callback);

}

CodePudding user response:

If you are trying to access data on multiple screens, the Provider package could help you. It stores global data accessible from all classes, without the need of creating constructors. It's good for big apps.

Here are some steps to use it (there is also a lot of info online):

  • Import provider in pubspec.yaml

  • Create your provider.dart file. For example:

    class HeroInfo with ChangeNotifier{
      String _hero = 'Ironman'
    
      get hero {
        return _hero;
      }
    
      set hero (String heroName) {
        _hero = heroName;
        notifyListeners();
      }
    }
    
  • Wrap your MaterialApp (probably on main.dart) with ChangeNotifierProvider.

    return ChangeNotifierProvider(
      builder: (context) => HeroInfo(),
      child: MaterialApp(...),
    );
    
  • Use it on your application! Call the provider inside any build method and get data:

    @override
    Widget build(BuildContext context){
      final heroProvider = Provider.of<HeroInfo>(context);
    
      return Column {
        children: [
          Text(heroProvider.hero) 
        ]
      }
    }
    
  • Or set data:

    heroProvider.hero = 'Superman';
    
  • Related