【问题标题】:How to make Flutter provider notifyListeners() from a factory?如何让工厂的 Flutter 提供者 notifyListeners()?
【发布时间】:2020-04-07 09:39:10
【问题描述】:

我有一个 Auth 类的提供者。当应用程序加载时,我调用一个 API,它返回带有数据的 json,我使用工厂方法 (Auth.fromJson) 将这些数据映射到 Auth 类中。映射完成后,我希望通知侦听器以便更新相关的 UI。所以我不能从工厂构造函数调用 notifyListeners() 因为我得到这个错误:

无法从工厂构造函数访问实例成员

为什么会这样?我可以实施什么解决方法?在工厂映射数据后,我需要能够以某种方式通知侦听器。

class Auth with ChangeNotifier {
  String token;
  String organisationId;
  String domain;
  String userId;

  Auth(
      {this.token,
      this.organisationId,
      this.domain,
      this.userId});

  factory Auth.fromJson(Map<String, dynamic> json) {
    Auth(
      token: json['token'],
      organisationId: json['organisationId'],
      domain: json['domain'],
      userId: json['userId'],
    );
    notifyListeners(); // Error here. 
    return Auth();
  }
}

【问题讨论】:

  • 您正试图在创建对象后立即通知Auth对象的侦听器。届时会有哪些听众?

标签: flutter dart flutter-provider


【解决方案1】:
  1. 工厂方法很像静态方法。您无法访问类变量和方法的方式也适用于工厂。
  2. notifyListeners();是 ChangeNotifier 类的一个方法,所以你不能通过任何静态方法或工厂方法访问它。
  3. 您将需要一个 Auth 实例来调用 notifyListeners();
  4. 如果你真的想观察 Auth 的变化,最好不要将 Auth 设为 ChangeNotifier,然后创建一个持有 Auth 值的 ChangeNotifer。以下是相关代码。

import 'package:flutter/material.dart';

class Auth{
  String token;
  String organisationId;
  String domain;
  String userId;

  Auth(
      {this.token,
      this.organisationId,
      this.domain,
      this.userId});

  factory Auth.fromJson(Map<String, dynamic> json) {
    return Auth(
      token: json['token'],
      organisationId: json['organisationId'],
      domain: json['domain'],
      userId: json['userId'],
    ); 
  }
}

class AuthChangeNotifier  with ChangeNotifier {
  Auth auth;
  onNewAuth(Auth newAuth){
    this.auth = newAuth;
    notifyListeners();
  }
}
  1. 您也可以将ValueNotifier&lt;Auth&gt; 用于此用例,并使用ValueListenableBuilder&lt;Auth&gt; 观察它

希望对您有所帮助,如果您有任何疑问,请告诉我。

【讨论】:

  • 谢谢。那么我会从哪里调用 onNewAuth 来传递 newAuth 呢?我在 http 响应处理程序中调用了 Auth.fromJson。我想当它返回时,我可以调用 AuthChangeNotifier.onNewAuth 传入较早返回的 Auth 实例...?
  • 你有一个现有的身份验证 --> 你从你的 api 收到新的身份验证 --> 从 JSON 解析它 --> 把它交给 ChangeNotifier --> 所有的监听器都会收到新的实例授权。就是这样。
  • @KalpeshKundanani 在上面的例子中你能解释一下你会如何“把它交给 ChangeNotifier”吗?
  • 我创建了一个名为 onNewAuth 的方法,我可以将它提供给 ChangeNotifier
猜你喜欢
  • 2020-07-16
  • 2021-08-28
  • 2021-03-17
  • 2014-03-03
  • 1970-01-01
  • 2015-03-04
  • 2016-02-18
  • 2015-07-22
  • 1970-01-01
相关资源
最近更新 更多