我有一个Auth类的提供者。应用加载时,我调用一个API,该API返回带有数据的json,这些数据我使用工厂方法(Auth.fromJson)映射到Auth类中。映射完成后,我希望通知侦听器,以便更新相关的UI。因此,轮到我无法从工厂构造函数调用notifyListeners(),因为出现此错误:
instance members cannot be accessed from a factory constructor
为什么会这样呢?我可以实现什么解决方法?工厂映射数据后,我需要能够以某种方式通知Listener。
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();
}
}
最佳答案
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();
}
}
ValueNotifier<Auth>
并使用ValueListenableBuilder<Auth>
观察它希望能有所帮助,如果您有任何疑问,请告诉我。
关于flutter - 如何使Flutter提供程序从工厂提供者notifyListeners()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330969/