gpt4 book ai didi

flutter - 如何使Flutter提供程序从工厂提供者notifyListeners()?

转载 作者:行者123 更新时间:2023-12-03 03:15:50 24 4
gpt4 key购买 nike

我有一个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();
}
}

最佳答案

  • 工厂方法非常类似于静态方法。无法访问类变量和方法的方法也适用于工厂。
  • notifyListeners();是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>观察它

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

    关于flutter - 如何使Flutter提供程序从工厂提供者notifyListeners()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330969/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com