I've 2 different pages:
page1 -> page2
I'm navigating from page 1 to 2, using a button and Navigator.push
. In both pages I simply show the value of a property called name
. In the first page I instantiate a ChangeNotifier model defined like this:
class User extends ChangeNotifier {
final String? name;
User(this.name);
set name(String? name) {
this.name = name;
notifyListeners();
}
}
Now, in the second page I want to change the property name
of the model, expecting that when I pop()
the backstack (e.g. pressing back arrow) and showing page1 it already shows the updated value. I'm passing the model via:
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => ChangeNotifierProvider.value(
value: user,
child: Page2Widget(),
),
))
In page2 I've wrapped with Consumer:
return Consumer<User>(builder: (context, user, child) {
return TextButton(
onPressed: () {
user.name = 'Child';
},
child: Text(user.name ?? ''),
);
});
When I click the TextButton
in page2 I got a stackoverflow error (well, it's quite weird posting it here). What is the reason of this loop? How can i solve? Is this the right approach to maintain the state between different pages? Thanks in advance.