LateInitializationError: Field 'snapshot' has not been initialized

LateInitializationError: Field 'snapshot' has not been initialized

此代码中没有错误,但此错误出现在 运行 之后,有人可以提供示例代码来解决以下错误吗? “LateInitializationError:字段 'snapshot' 尚未初始化,出现错误”

import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:utsucare_sample/PostScreen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  //Declaring some variables:
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;

  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('Article');

  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => PostScreen(snapshot: snap),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    subscription = collectionReference
        .orderBy('createdAt', descending: false)
        .snapshots()
        .listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text(
          'Messages',
          style: TextStyle(color: Colors.black87),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            SizedBox(
              height: 100,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: ListView.builder(
                  itemCount: snapshot.length,
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    return InkWell(
                      onTap: () {
                        passData(snapshot[index]);
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: CircleAvatar(
                              radius: 25.0,
                              backgroundImage: CachedNetworkImageProvider(
                                snapshot[index]['imgUrl'],
                              ),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
            const SizedBox(height: 50),
            Expanded(
              child: ListView.builder(
                itemCount: snapshot.length,
                shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    onTap: () {
                      passData(snapshot[index]);
                    },
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(15.0),
                          child: ListTile(
                            onTap: () {
                              passData(snapshot[index]);
                            },
                            leading: CircleAvatar(
                              radius: 30.0,
                              backgroundImage: CachedNetworkImageProvider(
                                  snapshot[index]['imgUrl']),
                            ),
                            title: Text(snapshot[index]['title']),
                            subtitle: Text(snapshot[index]['name']),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Android Studio 中的错误描述:

======== Exception caught by widgets library =======================================================
The following LateError was thrown building SearchScreen(dirty, state: _SearchScreenState):
LateInitializationError: Field 'snapshot' has not been initialized.

我在这里做错了什么?我真的很感激一些帮助。谢谢。

late List<DocumentSnapshot> snapshot; 

上面的快照被赋值后声明,但在build()方法内部使用之前没有被赋值,itemCount: snapshot.length导致你LateInitializationError

您可以通过像 List<DocumentSnapshot>? 快照一样使其为空安全或在小部件内添加空条件来避免上述错误。

您需要在 init() 中将快照列表初始化为:

  @override
  void initState() {
    super.initState();
    snapshots = [];// add this line
    subscription = collectionReference
        .orderBy('createdAt', descending: false)
        .snapshots()
        .listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

快照 = [];

在你的 initState() 中添加这一行