首页 > 解决方案 > 如何从工厂制作 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();
  }
}

标签: flutterdartflutter-provider

解决方案


  1. 工厂方法很像静态方法。您无法访问类变量和方法的方式也适用于工厂。
  2. 通知监听器();是 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<Auth>用于此用例并使用以下方法观察它ValueListenableBuilder<Auth>

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


推荐阅读