Home > Software design >  three clases use setState callback to update var on other class
three clases use setState callback to update var on other class

Time:01-21

I have next thre classes:

Shortly the scenario: have two classes MyApp1, MyApp2 and MyApp3,

MyApp3 updates the var count with callback (indeed updated), I would like to print it (count) on MyApp2, how can I setState also on MyApp2 so it will take effect?

my_app1.dart

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

  @override
  State<MyApp1> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final int count = 0;
  
  void callbakc() {
    setState(() {
      count  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
       Row(
         children:[
             MyApp2(),
             MyApp3(callback: callback), //suppose I have button on MyApp3, pressed it, and indded count increased by 1
         ]              
       ),
    );
  }
}

my_app2.dart

    class MyApp2 extends StatefulWidget {
          const MyApp({Key? key}) : super(key: key);
        
          @override
          State<MyApp2> createState() => _MyAppState();
    }
        
    class _MyAppState extends State<MyApp> {
          @override
          Widget build(BuildContext context) {
            return Container(
              child: Text(count), how can I see the update count? from MyApp1?
);
          }
    }

my_app3.dart

class MyApp3 extends StatefulWidget {
          const MyApp({Key? key}) : super(key: key);
        
          @override
          State<MyApp3> createState() => _MyAppState();
}
        
class _MyAppState extends State<MyApp> {
          @override
          Widget build(BuildContext context) {
            return Container();
          }
}

CodePudding user response:

use state management to do this. for example GetX. Type GetX in pub.dev and search.

Avoid setState. because it will increase the workload of your program.

For the answer to your question, see the link below.

Flutter Back button with return data

CodePudding user response:

Just pass the count parameter to MyApp2 so when your callback function run then it again render MyApp2 and update the count on MyApp2 also here is an example - Code in MyApp1

    MyApp2(count:count),

MyApp2 Code

  class MyApp2 extends StatefulWidget {
      const MyApp({Key? key,this.count}) : super(key: key);
      final int count;
      @override
      State<MyApp2> createState() => _MyAppState();
 }
    
class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Text($`enter code here count), how can I see the update count? from MyApp1?
 );
        }
    }
  • Related