skip to Main Content

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();
          }
}

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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?
     );
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search