Change state button on screen A when pressed something in screen B

Viewed 18

Imaging there's button with colour blue in screen A.
Then after clicking it navigates to screen B.
Then there's a button in screen B.
After clicking that it navigates to screen A.
While clicking it I want to change the colour of button in screen A.

How to do this? Using setState method or any kind of way to do? Please help me!

1 Answers

You can use a ValueNotifier or state-management like provider/riverpod/bloc. Also you can get data from .pop(YourValue).


final ValueNotifier<Color> myColorValue = ValueNotifier(Colors.blue);

class ScreenA extends StatelessWidget {
  const ScreenA({super.key});

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<Color>(
      valueListenable: myColorValue,
      builder: (context, value, child) => Scaffold(
        backgroundColor: value,
        body: Center(
            child: ElevatedButton(
          child: Text("nav To B"),
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => const ScreenB(),
            ));
          },
        )),
      ),
    );
  }
}

class ScreenB extends StatelessWidget {
  const ScreenB({super.key});

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<Color>(
      valueListenable: myColorValue,
      builder: (context, value, child) => Container(
        color: value,
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                myColorValue.value = Colors.pink; //changing the color
              },
              child: Text("change to pink"),
            ),
            ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("Go back")),
          ],
        ),
      ),
    );
  }
}
Related