我正在try 检索预定的结果.为此,我试着改变了线路:

CollectionReference _reference = FirebaseFirestore.instance.collection('table_name');

(指https://firebase.google.com/docs/firestore/query-data/order-limit-data):

CollectionReference _reference = FirebaseFirestore.instance.collection('table_name').orderBy("dlastupd");

在下面的代码.但是我得到了一个错误:

lib/main. dart:51:81:错误:不能将类型为'Query Map String,dynamic'的值赋给类型为'CollectionReference Object?&的变量<<>>< gt...

你能帮我解决这个问题吗?

非常感谢

代码:

void main() async {
   WidgetsFlutterBinding.ensureInitialized();
   await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  runApp(Home());
}

class Home extends StatelessWidget {

  // const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),

      routes: {
        '/': (context) => ItemList(),
        '/factfile': (context) => ItemDetails(),
      },
    );
  }
}

class ItemList extends StatelessWidget {
  ItemList({Key? key}) : super(key: key) {
    _stream = _reference.snapshots();
  }

  CollectionReference _reference = FirebaseFirestore.instance.collection('table_name');

  late Stream<QuerySnapshot> _stream;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Item List'),
      ),

      body: StreamBuilder<QuerySnapshot>(
        stream: _stream,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          //Check error
          if (snapshot.hasError) {
            return Center(child: Text('Some error occurred ${snapshot.error}'));
          }

          //Check if data arrived
          if (snapshot.hasData) {
            //get the data
            QuerySnapshot querySnapshot = snapshot.data;
            List<QueryDocumentSnapshot> documents = querySnapshot.docs;

            //Convert the documents to Maps
            List<Map> items = documents.map((e) =>
            {
              'name': e['name'],
              'dlastupd': e['dlastupd'],
              'dlastupd date': DateTime.fromMillisecondsSinceEpoch(e['dlastupd'] * 1000),
              'id': e.id,
            }).toList();

            // sort in descending date order
            items.sort((a, b) => b["dlastupd"].compareTo(a["dlastupd"]));

            //Display the list
            return ListView.builder(

                itemCount: items.length,
                itemBuilder: (BuildContext context, int index) {
                  //Get the item at this index
                  Map thisItem = items[index];
                  //Return the widget for the list items
                  return ListTile(

                    title: Text(formatDate(thisItem['dlastupd date'], [dd, '', M]) + " - " + thisItem['name']),
                    onTap: () {
                      Navigator.pushNamed(
                        context,
                        '/factfile',
                        arguments: {
                          'id': thisItem['id'],
                        },
                      );
                    },
                  );
                });
          }

          //Show loader
          return Center(child: CircularProgressIndicator());
        },
      ), //Display a list // Add a FutureBuilder
    );
  }
}

推荐答案

您会收到以下错误:

不能将‘Query<;Map<;字符串,Dynamic>;’类型的值赋给类型为‘CollectionReference<;Object?>;’的变量.

因为在下面的代码行中:

CollectionReference _reference = FirebaseFirestore.instance.collection('table_name').orderBy("dlastupd");

您试图将类型Query的对象赋给定义为类型CollectionReference的变量,这在Dart中是不可能的,因此出现了错误.请注意,继承关系是CollectionReference扩展Query,而不是相反.为了解决这个问题,请将上面的代码改为:

Query _reference = FirebaseFirestore.instance.collection('table_name').orderBy("dlastupd");
//👆

因为当您对CollectionReference对象调用.orderBy("dlastupd")时,结果对象是Query对象,notCollectionReference对象.

Flutter相关问答推荐

如何在Flutter 中不从getX库中初始化GetxController中的变量

Android Studio将不会构建iOS模拟器应用程序,因为plist.info有问题

如何在Flutter 中共享选定文本

脚本具有不受支持的MIME类型(';Text/html';).(messaging/failed-service-worker-registration)

将列表<;Events>;从Flutter 应用程序中的函数传回EventLoader属性时出错

如何在Flutter 中创造以下效果

使用 forLoops 在 Dart 中进行单元测试会返回 stackoverflow

Flutter:我的应用程序是否需要包含退款购买?

使用Flutter项目设置Firebase遇到困难?这些解决方案或许能帮到你!

使用堆栈的自定义按钮

为什么我们使用 RiverpodGenerator

Paypal 支付网关添加带有 magento 2 网络详细信息用户名、密码、签名 Magento 2 的 flutter 应用程序?

如何从底部导航栏打开 bottomModal 表?

如何建立最近的文件列表?

更改文本字段Flutter 中最大字母的 colored颜色

Flutter - 使用 pin 进行身份验证

Flutter 中的无效日期格式 2022 年 11 月 14 日

我一直在try 创建按钮以导航到第二页,但不知何故 RaisedButton 功能无法正常工作

运行Flutter 测试时出现 FirebaseAppPlatform.verifyExtends 错误

如何在flutter中共享容器和gridview之间的滚动条?