Home > Net >  LateInitializationError: Field 'snapshot' has not been initialized
LateInitializationError: Field 'snapshot' has not been initialized

Time:04-11

There is no error in this code but this error is coming after running, Can someone please provide an example code of what's needed to solve for the error below? "LateInitializationError: Field 'snapshot' has not been initialized, got error"

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']),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Error Description in Android Studio:

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

What am I doing wrong here? I'd really appreciate some help. Thank you.

CodePudding user response:

You need to initialise the snapshot list in the init() as:

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

CodePudding user response:

late List<DocumentSnapshot> snapshot; 

The above snapshot is assigned to be declared later, but it's not assigned before it is used inside in build() method, itemCount: snapshot.length causing LateInitializationError for you.

You can avoid the above error by making it null safe like List<DocumentSnapshot>? snapshot or adding a null condition inside the widget.

CodePudding user response:

snapshots = [];

Add this line in your initState()

  • Related