Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

flutter - How can I sort List<Map<String, dynamic>>?

List<Map<String, dynamic>> list=[
{_id: 1, product_name: Name1, product_company: T, product_barcode: 1, product_shopping_date: 1610467398845, product_expiration_date: 1610414640000, product_origin_country: Musterherstellungsland, product_kind_of_crowd: Stück, product_availability: 1}, 
{_id: 2, product_name: Name2, product_company: T, product_barcode: 1, product_shopping_date: 1610467518522, product_expiration_date: 1610406000000, product_origin_country: Musterherstellungsland, product_kind_of_crowd: Stück, product_availability: 1}, 
{_id: 3, product_name: Name3, product_company: T, product_barcode: 1, product_shopping_date: 1610467551377, product_expiration_date: 1610423280000, product_origin_country: Musterherstellungsland, product_kind_of_crowd: Stück, product_availability: 1}]

How can I sort this list by product_expiration_date ?

I have tried this

list.sort((a, b) {
      return (a['product_expiration_date']).compareTo(b['product_expiration_date']);
    });

But this was the result:

E/flutter (  617): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Unsupported operation: read-only
E/flutter (  617): #0      QueryResultSet.[]= (package:sqflite_common/src/collection_utils.dart:108:5)
E/flutter (  617): #1      Sort._insertionSort (dart:_internal/sort.dart:70:10)
E/flutter (  617): #2      Sort._doSort (dart:_internal/sort.dart:58:7)
E/flutter (  617): #3      Sort.sort (dart:_internal/sort.dart:33:5)
E/flutter (  617): #4      ListMixin.sort (dart:collection/list.dart:355:10)
...

Does someone have a solution?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your list is immutable so it's "read-only" as the error suggests. You have to create a modifiable copy of the list so that the sort function can modify it. Then you can use your existing sort implementation.

List<Map<String, dynamic>> listCopy = List.of(list);

listCopy.sort((a, b) {
  return (a['product_expiration_date']).compareTo(b['product_expiration_date']);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...