Home > Software design >  How to use variable in Flutter Firebase Collection order by statement?
How to use variable in Flutter Firebase Collection order by statement?

Time:11-15

I'd like to be able to use a variable (state?) to populate the orderBy statement in my FirebaseFirestore collection statement.

The code below runs fine until I uncomment .orderBy(sortBy, descending: sortDesc);, then I receive red squiggles error indicator with explanation The instance member 'sortBy' can't be accessed in an initializer.

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class HomePage extends StatelessWidget {

  final String sortBy = "timestamp";
  final bool sortDesc = true;

  final itemList = FirebaseFirestore.instance
      .collection("simple")
      .orderBy("item", descending: false);           // <-- Works

      // .orderBy(sortBy, descending: sortDesc);     // <-- Does not work
      // ERROR: The instance member 'sortBy' can't be accessed in an initializer. 

  //--- Build Home Page Widget
  @override
  Widget build(BuildContext context) {

      return StreamBuilder(
        stream: itemList.snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

          ...

        }
      );

  }
}

Ultimately I'd like to be able to control the sortBy and sortDesc variables from a setting in the UI.

I'm relatively new to Flutter and I'm trying to figure out how to fix this in the most Flutter-appropriate way. Any comments and/or suggestions are welcome. Thanks!

Final Working Code, based on John's answer...

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class HomePage extends StatelessWidget {

  final String sortBy = "timestamp";
  final bool sortDesc = true;

  // CHANGED itemList to Stream...
  Stream<QuerySnapshot<Map<String, dynamic>>> itemList()=>
      FirebaseFirestore.instance
          .collection("simple")
          .orderBy(sortBy, descending: sortDesc).snapshots();

  //--- Build Home Page Widget
  @override
  Widget build(BuildContext context) {

      return StreamBuilder(
        stream: itemList(),      // CHANGED stream
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

          ...

        }
      );

  }
}

CodePudding user response:

you cant access variable outside of a method. So to fix that, convert your itemList into a function.

Stream<List<Item>> itemList()=>
 FirebaseFirestore.instance
      .collection("simple")
      .orderBy("item", descending: false);          
      .orderBy(sortBy, descending: sortDesc).snapshots();

  • Related