如何在Flutter Firebase Collection order by语句中使用变量?

krugob8w  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(98)

我希望能够使用变量(state?)来填充FirebaseFirestore集合语句中的orderBy语句。

下面的代码运行良好,直到我取消注解.orderBy(sortBy, descending: sortDesc);,然后我收到红色的波浪线错误指示符,并解释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) {

          ...

        }
      );

  }
}

最后,我希望能够通过UI中的设置来控制sortBy和sortDesc变量。
我对Flutter比较陌生,我正在尝试用最适合Flutter的方式来解决这个问题。欢迎任何意见和/或建议。谢谢!

根据John的回答,最终工作代码...

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) {

          ...

        }
      );

  }
}
pjngdqdw

pjngdqdw1#

你不能访问方法外变量,所以要解决这个问题,把你的itemList转换成一个函数。

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

相关问题