【发布时间】: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