flutter - 如何从工厂制作 Flutter 提供者 notifyListeners()?
问题描述
我有一个 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();
}
}
解决方案
- 工厂方法很像静态方法。您无法访问类变量和方法的方式也适用于工厂。
- 通知监听器();是 ChangeNotifier 类的一个方法,因此您不能通过任何静态方法或工厂方法访问它。
- 您将需要一个 Auth 实例来调用 notifyListeners();
- 如果你真的想观察 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();
}
}
- 您也可以
ValueNotifier<Auth>
用于此用例并使用以下方法观察它ValueListenableBuilder<Auth>
希望对您有所帮助,如果您有任何疑问,请告诉我。
推荐阅读
- rust - 对迭代器进行分区时,Vec 没有实现特征 Extend
- c++ - C++、CMake 和 Xcode 符号导航器
- reactjs - SpringBoot + WebFlux + Reactjs Server Sent Events onmessage not fire up
- c# - Xamarin 表单 - Java.Interop.lz4 访问被拒绝错误
- wordpress - WP Query - if/else 使用自定义字段
- reactjs - 将函数组件中的变量传递给类组件
- python-3.x - 如何模拟 elasticsearch.helpers.bulk
- matlab - 根据特定列对矩阵进行排序,并使用另一列对其进行进一步排序,同时保持第一排序顺序
- database - 如何在 Google App Engine 中使用游标从 db 数据库中批量获取记录?
- java - 字符串类型不允许重音元音