Home > Software engineering >  flutter how to Data send recieve
flutter how to Data send recieve

Time:12-28

How can I change the visibility property of the button on the X screen from a button on the Y screen.

CodePudding user response:

One popular approach (using the provider architecture) would be something like this:

Define a provider that handles all the logic and holds your data:

class MyProvider extends ChangeNotifier {
  bool showMyButton = false;

  MyProvider() {}

  void showButton() {
    showMyButton = true;
    // This line notifies all consumers
    notifyListeners();
  }

  void refresh() {
    notifyListeners();
  }
}

To access the provider everywhere you need to register it:

void main() => runApp(
      // You can wrap multiple providers like this
      MultiProvider(
        providers: [
          ChangeNotifierProvider<MyProvider>(create: (_) => MyProvider()),
        ],
        child: const MyApp(),
      ),
    );

On the button that you want to control you can use a Consumer to listen to the providers values:

Consumer<MyProvider>(builder: (_, model, __) {
     return Visibility(
             visible: model.showMyButton,
             child: MaterialButton(...),
     );
})

Now in your second screen you can access that provider with:

Provider.of<MyProvider>(context, listen: false)
                        .showButton();

However you might have to call notifyListener one more time when returning from screen Y to screen X:

await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => ScreenY()));
Provider.of<MyProvider>(context, listen: false).refresh();

Keep in mind that there is a lot more to provider so please have a look at their official docs.

Also be aware of the fact that there are easier ways to just pass data between screens but you will often arrive at a point where you will need a better way of managing state and provider provides just that ;)

CodePudding user response:

You can pass the data via push and pop of navigation. Or else use ChangeNotifier class to notify the state of button easily.

  • Related