top of page

[Flutter/dart]Sorting and extracting Map elements


Overview


When creating an application with Flutter, I often store user data etc. in Map (because it is troublesome to deal with index deviation when deleting data with list).

In that case, when displaying the data on the screen, it is necessary to devise to specify the order or extract only the data under specific conditions. (C # dictionary can be treated like list ...)


Method


If you convert Map to List of MapEntry, you can use methods such as where() and sort(). After that, the argument should be taken in List <MapEntry> on the user side (basically it should be build() of Widget).


sorting


In the following, the comparison method is passed as a delegate so that it can handle multiple sorting methods.

class UserData{
  String name;
  int score;

  UserData({this.name, this.score});
}


class MyHomePageState extends State<MyHomePage> {

  Map<int, UserData> data;

  @override
  void initState() {
    data={
      0: UserData(name: "Alice", score: 90),
      1: UserData(name: "Bob", score: 87),
      2: UserData(name: "Charlie", score: 98),
    };
  }

  @override
  Widget build(BuildContext context) {

    //Sort in ascending order of score
    var _entries=_orderData(data, (a, b) => (a.value as 
    UserData).score.compareTo((b.value as UserData).score));

    return Scaffold(
        appBar: AppBar(
          title: Text('demo'),
        ),
        body: Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: _entries.map((e) => ListTile(
              title: Text(
                "${e.value.name}: ${e.value.score}",
                style: TextStyle(
                  fontSize: 16
                ),
              ),
            )).toList(),
          )
        )
    );
  }

  //this!
  List<MapEntry> _orderData(Map<int, dynamic>maps, int 
  Function(MapEntry<int, dynamic>, MapEntry<int, dynamic>) sorter){
    return maps.entries.toList()..sort((a, b)=> sorter(a, b));
  }
}


extract


Similarly, create a method that takes a delegate that represents the condition as an argument.

List<MapEntry> _selectData(Map maps, bool Function(MapEntry) predicate){
  return maps.entries.toList().where((element) => 
      predicate(element)).toList();
}

@override
Widget build(BuildContext context) {

  //Extract data with a score of 90 or higher
  var _entries=_selectData(data, (e) => e.value.score>90);

  return Scaffold(
      appBar: AppBar(
        title: Text('demo'),
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: _entries.map((e) => ListTile(
            title: Text(
              "${e.value.name}: ${e.value.score}",
              style: TextStyle(
                fontSize: 16
              ),
            ),
          )).toList(),
        )
      )
  );
}

Lastly


I use Map for ease of searching and deleting, and List <MapEntry> for easy sorting and condition extraction when listing in widget .

Recent Posts

See All

Kommentare


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page