Search code examples
sortingdictionarydartfluttersplay-tree

How to use a SplayTreeMap on Firebase snapshot dictionary in dart/Flutter?


I'm successfully getting data back through StreamBuilder and need to sort it. How can I sort a Map of my snapshot data by keys? Also, If you give an example of doing this my value that would help also. I think I want to do a SplayTreeMap, but if there is a better way please provide. Here is my dictionary...

{Vid2: {imageString: https://i.ytimg.com/vi/Amq-qlqbjYA/mqdefault.jpg, title: BLACKPINK - '마지막처럼 (AS IF IT'S YOUR LAST)' M/V, rank: 2, videoID: Amq-qlqbjYA}, Vid10: {imageString: https://i.ytimg.com/vi/KSH-FVVtTf0/mqdefault.jpg, title: EXO 엑소 'Monster' MV, rank: 10, videoID: KSH-FVVtTf0}, Vid6: {imageString: https://i.ytimg.com/vi/BVwAVbKYYeM/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ DOPE(쩔어), rank: 6, videoID: BVwAVbKYYeM}, Vid3: {imageString: https://i.ytimg.com/vi/m8MfJg68oCs/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ Boy In Luv(상남자), rank: 3, videoID: m8MfJg68oCs}, Vid4: {imageString: https://i.ytimg.com/vi/9pdj4iJD08s/mqdefault.jpg, title: BLACKPINK - '불장난 (PLAYING WITH FIRE)' M/V, rank: 4, videoID: 9pdj4iJD08s}, Vid1: {imageString: https://i.ytimg.com/vi/3s1jaFDrp5M/mqdefault.jpg, title: EPIK HIGH - 'BORN HATER' M/V, rank: 1, videoID: 3s1jaFDrp5M}, Vid8: {imageString: https://i.ytimg.com/vi/3QAcvc4Ysl0/mqdefault.jpg, title: LONNI - LA KPOP 2, rank: 8, videoID: 3QAcvc4Ysl0}, Vid5: {imageString: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, title: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V, rank: 5, videoID: 2ips2mM7Zqw}}

I would like to display it either by keys... Vid1, Vid2, Vid3...

or by values like rank ie... Vid1:rank "1", Vid2: rank "2", Vid3: rank "3"...


Solution

  • If the source is a map, this should do what you want:

    final sorted = new SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));
    

    DartPad example