2

我正在尝试学习 Riverpod,并且我有一个ChangeNotifierProvider需要使用从异步操作返回的值初始化的几个字段。这可能吗,因为我知道我无法ChangeNotifierProvider异步创建?

例子ChangeNotifierProvider

class SomeState extends ChangeNotifier {
  String email = '';

  // needs to be set to value returned from
  // shared preferences upon init
}

如果不可能,是否有另一个提供程序可以更好地知道我想将其值初始化为异步方法的返回值?

4

1 回答 1

3

是的,这可能是 Abion47 的评论。让我在下面的代码中显示更多细节

class EmailNotifier extends ChangeNotifier {
  String email = '';

  void load() {
    functionReturnFuture.then(value) {
      setEmail(value);
    }
  }

  void setEmail(String value) {
    // email loaded but not changed, so no need to notify the listeners
    if(value == email) return;

    // email has loaded and change then we notify listeners
    email = value;
    notifyListeners();
  }
}


var emailNotifier = ChangeNotifierProvider<EmailNotifier>((ref) {
  var notifier = EmailNotifier();

  // load the email asynchronously, once it is loaded then the EmailNotifier will trigger the UI update with notifyListeners
  notifier.load();
  return notifier;
});

由于我们独立于 Flutter UI 管理状态,因此没有什么会阻止您运行代码来触发状态更改,例如在我们的例子中是notifier.load()

notifier.load()和 email 设置之后,提供者将使用notifyListeners()触发 UI 更改。

您可以使用 FutureProvider 获得类似的结果。

于 2020-11-21T10:09:05.573 回答