Home > OS >  flutter firebase realtime database: how to get the result of orderByValue as a List<String>?
flutter firebase realtime database: how to get the result of orderByValue as a List<String>?

Time:12-06

I keep list of hashtags and their appearance in realtime db.

enter image description here

And I want to make a service class with a function to retrieve hashtags as a List in descending order of appearance. So below is the preferred result.

List<String> expHashList = [개발자, 인사담당자, VC, 작가, 경영자];
List<String> topicList = [커리어, 채용, 이직, 리더십, 조직문화];

I tried below but it returns empty list([]).

class HashtagService {
  static final HashtagService _instance = HashtagService._internal();
  factory HashtagService() => _instance;

  late final DatabaseReference _database;

  HashtagService._internal() {
    _database = FirebaseDatabase.instance.reference().child('/hashtags');
  }

  List<String> getSuggestion(String type) {
    if (type == 'exp') {
      var query = _database.child('expHash').orderByValue().limitToLast(10);
      return FirebaseList(query: query).cast<String>();
    } else {
      var query = _database.child('topic').orderByValue().limitToLast(10);
      return FirebaseList(query: query).cast<String>();
    }
  }
}

This is second approach but I can't figure out type casting and sort compare function to work correctly. And this version returns Future<List> instead.

  Future<List<String>> getSuggestion() async {
    return await _database.child('expHash').get().then((snapshot) {
      Map<String, int> map = snapshot.value;   // type error -> <dynamic, dynamic>
      List<String> hashtagList = map.keys.toList();   
      hashtagList.sort((k1, k2) => map[k1]! > map[k2]! ? 1 : -1);   // is this right?
      return hashtagList;
    });
  }

What's the best way to get the result of orderByValue(or orderByKey or orderByChild) as a List or List?


EDIT(Answer)

List<String?> _resultList = [];

var query = _database.child('topic').orderByValue().limitToLast(10);
query.onChildAdded.listen((Event event) {
    _resultList.add(event.snapshot.key);
});
return await query.get().then((snapshot) {return _resultList;});

But this returns Future<List<String>> instead. So I had to use FutureBuilder to process output.

CodePudding user response:

In recent versions of the FlutterFire library for Firebase you should be able to use snapshot.value.values to get an ordered list of the result snapshots of a query.

If that is not working, the previous approach is either Flutter: Firebase Real-Time database orderByChild has no impact on query result or Flutter Firebase Database wrong timestamp order or

  • Related