【问题标题】:Flutter Riverpod - Initialize with async valuesFlutter Riverpod - 使用异步值初始化
【发布时间】:2021-01-24 19:54:57
【问题描述】:

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

例如ChangeNotifierProvider

class SomeState extends ChangeNotifier {
  String email = '';

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

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

【问题讨论】:

  • 强制状态等待未来的返回值可能会停止整个应用程序。相反,在您的状态初始化中调用 async 方法,并在完成后保存值并调用 notifyListeners() 以重建任何侦听小部件。
  • 谢谢@Abion47,这是有道理的。打算尝试重构。
  • 你可以添加一个“bool isLoading”标志
  • 谢谢@RémiRousselet,但我不确定我应该把这个标志放在哪里?
  • 在你的 SomeState 类中

标签: flutter dart flutter-provider riverpod


【解决方案1】:

是的,就像 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() 并设置电子邮件后,提供商将使用 notifyListeners() 触发 UI 更改。

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

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2021-03-17
    相关资源
    最近更新 更多