简体   繁体   English

在不同页面之间保留 state

[英]Preserving state between different pages

I've 2 different pages:我有 2 个不同的页面:

page1 -> page2

I'm navigating from page 1 to 2, using a button and Navigator.push .我正在使用按钮和Navigator.push从第 1 页导航到第 2 页。 In both pages I simply show the value of a property called name .在这两个页面中,我只显示了一个名为name的属性的值。 In the first page I instantiate a ChangeNotifier model defined like this:在第一页中,我实例化了一个 ChangeNotifier model,定义如下:

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 (eg pressing back arrow) and showing page1 it already shows the updated value.现在,在第二页中,我想更改 model 的属性name ,期望当我pop()返回堆栈(例如按返回箭头)并显示 page1 时,它已经显示了更新的值。 I'm passing the model via:我通过 model 通过:

Navigator.push(
          context,
          MaterialPageRoute(
            builder: (BuildContext context) => ChangeNotifierProvider.value(
              value: user,
              child: Page2Widget(),
            ),
          ))

In page2 I've wrapped with Consumer:在第 2 页中,我使用了消费者:

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).当我单击 page2 中的TextButton时,出现 stackoverflow 错误(好吧,在这里发布它很奇怪)。 What is the reason of this loop?这个循环的原因是什么? How can i solve?我该如何解决? Is this the right approach to maintain the state between different pages?这是在不同页面之间维护 state 的正确方法吗? Thanks in advance.提前致谢。

You get a stackoverflow error because of your setter function由于您的设置器 function,您会收到 stackoverflow 错误

set name(String name){
  this.name = name;
  notifyListeners();
}

This function gets called infinite times, because you call it again by using this.name = name and you get recursion.这个 function 被无限次调用,因为你使用this.name = name再次调用它,你会得到递归。 You can change your function to this one:您可以将您的 function 更改为此:

void setName(String name){
  this.name = name;
  notifyListeners();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM