微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Bloc - Flutter 通过另一个类中的 getter 访问 arrayList 值

如何解决如何使用 Bloc - Flutter 通过另一个类中的 getter 访问 arrayList 值

我试图在 blocProvider 的帮助下通过 getter 将 arrayList 数据获取到另一个类中,但在另一个类中它给出了以下错误

The getter 'value' isn't defined for the type 'BehaviorSubject<List<Medicine>>'.
Try importing the library that defines 'value',correcting the name to the name of an existing getter,or defining a getter or field named 'value'

这里是 Bloc 类,我在那里违抗 getter获取 arrayList 值

class GlobalBloc {
  BehaviorSubject<List<Medicine>> _medicineList$;
  BehaviorSubject<List<Medicine>> get medicineList$ => _medicineList$; //getter  <--


  GlobalBloc() {
    _medicineList$ = BehaviorSubject<List<Medicine>>.seeded([]);
    makeMedicineList();
  }


  Future makeMedicineList() async {
    SharedPreferences sharedUser = await SharedPreferences.getInstance();
    List<String> jsonList = sharedUser.getStringList('medicines');
    List<Medicine> prefList = [];
    if (jsonList == null) {
      return;
    } else {
      for (String jsonMedicine in jsonList) {
        Map userMap = jsonDecode(jsonMedicine);
        Medicine tempMedicine = Medicine.fromJson(userMap);
        prefList.add(tempMedicine);
      }
      _medicineList$.add(prefList);
    }
  }

  void dispose() {
    _medicineList$.close();
  }
}

这是我尝试获取 arrayList 值的另一个

@override
  Widget build(BuildContext context) {
    final GlobalBloc _globalBloc = Provider.of<GlobalBloc>(context);

... 

 for (var medicine in _globalBloc.medicineList$.value) { //ERROR <--
        if (medicineName == medicine.medicineName) {
             return;
        }
 }
                     
}

错误看起来像这样

enter image description here

解决方法

现在,你可以试试这个,从 Bloc 获取价值

List<Medicine> medList = [];
medList = await _globalBloc.medicineList$.first;

N.B:由于声誉较低,无法发表评论。这就是为什么发布作为答案的原因。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。