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

- 2,246
- 2
- 14
- 37

- 33
- 3
-
Are you referring to the fact that you want to modify a view of another screen while in another? – Elvis Salabarria Aquino Dec 27 '21 at 19:08
-
Does this answer your question? [Flutter, Navigator 2.0: How to return data from a screen?](https://stackoverflow.com/questions/66279804/flutter-navigator-2-0-how-to-return-data-from-a-screen) – bartektartanus Dec 28 '21 at 15:43
2 Answers
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 ;)

- 2,246
- 2
- 14
- 37
You can pass the data via push and pop of navigation. Or else use ChangeNotifier class to notify the state of button easily.

- 419
- 3
- 11