首页 > 解决方案 > Flutter GetX 无法分配 Set到 RxSet

问题描述

我正在开发一个应用程序并遇到了一个问题,这不会导致错误,但对我来说非常令人沮丧。

情况是我有一个自定义类对象的 RxSet,默认初始化为空集。当我从服务器获取数据时,我想将结果分配给这个集合。正如 GetX 建议的那样,我应该像myRxSet = dataFetchedFromServer. 这给了我一个编译时错误。myRxSet.value = dataFetchedFromServer仍然有效,但提供了我不应该分配给 .value 属性的信息。

示例代码如下所示

RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

Future<void> syncData() async {
   myCustomClassEntries = await _fetchDataFromServer(); // this gives me compile time error
   myCustomClassEntries.value = await _ fetchDataFromServer(); // this gives me a warning that RxSet is not intented to be used this way.
}

GetX 版本:^4.3.4 Flutter 版本:2.2.3 Dart 版本:2.13.4

知道我做错了什么吗?

编辑


_fetchDataFromServer()在这种情况下没关系,只是想为这个问题提供一些背景。就这么简单:

RxSet<MyCustomClass> myCustomClassEntries = Set<MyCustomClass>().obs;

// This line gives me a compile time error. It says Set<MyCustomClass> can't be assigned to RxSet<MyCustomClass>
myCustomClassEntries = new Set<MyCustomClass>();

// This line works, just like everywhere else with GetX, but says .value is no longer intented to be used on RxList, RxSet or RxMap. It recommends to use the syntax above, which gives the error.
myCustomClassEntries.value = new Set<MyCustomClass();

来自 GetX 更新日志

更改:您不需要访问原语的“.value”属性。对于字符串,您需要插值。对于 num、int、double,您将拥有普通运算符,并将其用作 dart 类型。这样,.value 可以专门用于 ModelClasses。例子:

var name = "Jonny" .obs;
// usage:
Text ("$name");

var count = 0.obs;
// usage:
increment() => count ++;
Text("$count");

因此:从本版本开始,List、Map、Set、num、int、double 和 String 将不再使用 .value 属性。

注意:这些更改不是重大更改,但是,您可能错过了文档的详细信息,因此如果您遇到以下消息:“成员 'value' 只能在 'rx_list.dart' 的子类的实例成员中使用”您只需从列表中删除“.value”属性,一切都会按计划进行。地图和集合也是如此。

标签: flutterflutter-getx

解决方案


总之,list在 Getx 中使用 a 时,不需要使用.value.

...
myCustomClassEntries = Set<MyCustomClass>().obs; // just add .obs and treat it like a regular list. 
final object = MyCustomClass();
myCustomClassEntries.add(object); // no error here and not using .value

我要求该_fetchDataFromServer()功能,因为它对您要返回的内容很重要。但无论如何,返回一个 observableSet<MyCustomClass>()就不会出现类型转换错误。

跟进问题后更新:

只需RxSet<MyCustomClass>从您的_fetchDataFromServer函数返回一个,以便您有匹配的类型。

Future<RxSet<MyCustomClass>> _fetchDataFromServer() async {
  final tempList = Set<MyCustomClass>().obs;
// ... your code that populates list from server
  return tempList;
}

您无需清除列表。下面将myCustomClassEntries仅使用函数返回的内容进行更新。

myCustomClassEntries = await _fetchDataFromServer();

推荐阅读