如何以字符串格式按日期对对象列表进行排序



我有一个List,它有一个名为updatedAt的参数,它是一个具有DateTime.now().toString().substring(0, 19)的String,我需要按日期(最新的(位置0(到最旧的(最后的位置((组织它,但当我尝试使用list.sort((a, b) => a.updatedAt.compareTo(b.updatedAt))时,我遇到了以下错误,我必须将String转换为DateTime还是其他什么?

class Product {
String id;
String image;
String name;
String desc;
int price;
int quantity;
String category;
String createdAt;
String updatedAt;
bool active;
Product({this.id, this.image, this.name, this.desc, this.price, this.quantity,
this.category, this.createdAt, this.updatedAt, this.active}){
quantity = 1;
active = true;
}
Future<void> getProducts() async {
List<Product> products = [];
products.addAll(await getProductsFromFirestore()); // Here I add products from Firebase...
print(products[0].updatedAt); // 2020-07-21 12:31:08
print(products[1].updatedAt); // 2020-07-21 12:31:13

products.sort((a, b) => a.updatedAt.compareTo(b.updatedAt));
}

错误(Flutter Web(:

Error: Expected a value of type 'Comparable<dynamic>', but got one of type 'Product'
at Object.throw_ [as throw] (http://localhost:53122/dart_sdk.js:4339:11)
at Object.castError (http://localhost:53122/dart_sdk.js:4310:15)
at Object.cast [as as] (http://localhost:53122/dart_sdk.js:4626:17)
at Function.as_C [as as] (http://localhost:53122/dart_sdk.js:4271:19)
at http://localhost:53122/dart_sdk.js:15079:98
at Function._insertionSort (http://localhost:53122/dart_sdk.js:23099:55)
at Function._doSort (http://localhost:53122/dart_sdk.js:23086:24)
at Function.sort (http://localhost:53122/dart_sdk.js:23068:22)
at Array.[dartx.sort] (http://localhost:53122/dart_sdk.js:15079:26)
at RxList.new.sort (http://localhost:53122/packages/get/src/rx/rx_impl.dart.lib.js:610:27)
at home_controller.HomeController.new.getProductsFromController (http://localhost:53122/packages/site_catalogo_modelo/controllers/home_controller.dart.lib.js:94:21)
at product_controller.ProductController.new.getProducts (http://localhost:53122/packages/site_catalogo_modelo/controllers/home_controller.dart.lib.js:212:74)
at getProducts.next (<anonymous>)
at http://localhost:53122/dart_sdk.js:37340:33
at _RootZone.runUnary (http://localhost:53122/dart_sdk.js:37194:58)
at _FutureListener.thenAwait.handleValue (http://localhost:53122/dart_sdk.js:32178:29)
at handleValueCallback (http://localhost:53122/dart_sdk.js:32725:49)
at Function._propagateToListeners (http://localhost:53122/dart_sdk.js:32763:17)
at _Future.new.[_completeWithValue] (http://localhost:53122/dart_sdk.js:32606:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:53122/dart_sdk.js:32628:35)
at Object._microtaskLoop (http://localhost:53122/dart_sdk.js:37455:13)
at _startMicrotaskLoop (http://localhost:53122/dart_sdk.js:37461:13)
at http://localhost:53122/dart_sdk.js:32980:9

问题是我没有使用List,我使用get包进行状态管理,我的产品列表是一个可观察的,它在另一个变量中有List的efl,因此排序没有正常工作,而且我必须更改为"b.updatedAt.compareTo(a.updatedAt(("才能按我需要的顺序获得列表。

相关内容

  • 没有找到相关文章

最新更新