简体   繁体   中英

snapshot.data is null in flutter firebase

my widget tree is stuck on stream builder condition ie !snapshot.hasdata so data of snapshot has null . I checked in firestore but there is data so is there any wrong in firebase file because the data is not displayed. how to get rid of this even I have add the data I hope this question also helps to other in future

class TodoList extends StatefulWidget {
  @override
  State<TodoList> createState() => _TodoListState();
}

class _TodoListState extends State<TodoList> {
  TextEditingController todoTitleController = TextEditingController();

  bool iscomplete = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: primarycolor,
      body: SafeArea(
          child: StreamBuilder<List<Todolist>>(
              stream: DatabaseService().listTodo(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Loading();
                }
                print(snapshot.data![0].title);

                List<Todolist> todos = snapshot.data;

                return Padding(
                  padding: EdgeInsets.all(25.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // ignore: prefer_const_constructors
                      Center(
                        child: const Text(
                          'All Todos',
                          style: TextStyle(
                              fontSize: 30,
                              fontWeight: FontWeight.bold,
                              color: Colors.white),
                        ),
                      ),
                      // ignore: prefer_const_constructors
                      Divider(),
                      // ignore: prefer_const_constructors
                      SizedBox(height: 20),
                      ListView.separated(
                          separatorBuilder: (context, index) => Divider(
                                color: Colors.grey[800],
                              ),
                          shrinkWrap: true,
                          itemCount: todos!.length,
                          itemBuilder: (context, index) {
                            return Dismissible(
                              key: Key(todos![index].title),
                              background: Container(
                                padding: EdgeInsets.only(left: 20),
                                alignment: Alignment.centerLeft,
                                child: Icon(Icons.delete),
                                color: Colors.red,
                              ),
                              onDismissed: (direction) async {
                                await DatabaseService()
                                    .removeTodo(todos![index].id);
                              },
                              child: ListTile(
                                onTap: () {
                                  setState(() {
                                    iscomplete = !iscomplete;
                                  });
                                },
                                leading: Container(
                                  padding: EdgeInsets.all(4),
                                  height: 43,
                                  width: 33,
                                  decoration: BoxDecoration(
                                    color: secondarycolor,
                                    shape: BoxShape.circle,
                                  ),
                                  child: iscomplete
                                      ? Icon(
                                          Icons.check,
                                          color: Colors.grey[200],
                                        )
                                      : Container(),
                                ),
                                title: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      todos![index].title,
                                      style: TextStyle(
                                          fontSize: 20,
                                          fontWeight: FontWeight.w600,
                                          color: Colors.grey[200]),
                                    ),

here my firebase file:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:todolist/models/model.dart';

class DatabaseService {
  CollectionReference todosCollection =
      FirebaseFirestore.instance.collection("Todos");

  Future createNewTodo(String title) async {
    return await todosCollection.add({
      "title": title,
      "iscomplete": false,
    });
  }

  Future completTask(id) async {
    await todosCollection.doc(id).update({"iscomplete": true});
  }

  Future removeTodo(uid) async {
    await todosCollection.doc(uid).delete();
  }

  List<Todolist> todoFromFirestore(QuerySnapshot snapshot) {
    if (snapshot != null) {
      return snapshot.docs.map((e) {
        return Todolist(
          iscomplete: e["iscomplete"],
          title: e["title"],
          id: e.id,
        );
      }).toList();
    } else {
      return [];
    }
  }

  Stream<List<Todolist>> listTodo() {
    return todosCollection.snapshots().map(todoFromFirestore);
  }
}

This is because of snapshot has connection state

StreamBuilder(
        stream: stream,
        builder: (context, snapshot) {
          // Check for errors
          if (snapshot.hasError) {
            return SomethingWentWrong();
          }

          // Once complete, show your application
          if (snapshot.connectionState == ConnectionState.done) {
            // here you should do your worj
          }

          // Send updates to the widget
          if (snapshot.connectionState == ConnectionState.active) {
            // or here if you take data in pages
          }

          // Otherwise, show something whilst waiting for initialization to complete
          return LoadingWidget();
        },
      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM