0

The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(dirty, state: _FutureBuilderState<DocumentSnapshot<Map<String, dynamic>>>#c2b0e): The method 'data' was called on null. Receiver: null Tried calling: data()

in chatApp :- here source code highlighted

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobkar/public/model/user_model.dart';
import 'package:jobkar/public/view/navigation/message/chat_room.dart';

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

  @override
  State<Message> createState() => _MessageState();
}

class _MessageState extends State<Message> {
  final currentUser = FirebaseAuth.instance.currentUser;
  final searchController = TextEditingController();
  String search = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              height: 50,
              width: double.infinity,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10), color: Colors.white),
              child: Row(
                children: [
                  Flexible(
                    child: TextFormField(
                      controller: searchController,
                      onChanged: (value) {
                        search = value;
                      },
                      decoration: InputDecoration(
                          hintText: 'Search person',
                          border: InputBorder.none,
                          prefixIcon: const Icon(
                            Icons.dehaze,
                            size: 26,
                            color: Colors.black54,
                          ),
                          hintStyle: GoogleFonts.raleway(
                              fontSize: 16, fontWeight: FontWeight.normal)),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(5.0),
                    child: Container(
                      height: 40,
                      width: 40,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.black54),
                      child: Center(
                        child: IconButton(
                          onPressed: () {
                            setState(() {});
                          },
                          icon: const Icon(
                            Icons.search,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: StreamBuilder(
              stream: FirebaseFirestore.instance
                  .collection('users')
                  .doc(currentUser!.uid)
                  .collection('message')
                  .snapshots(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: CircularProgressIndicator(
                      color: Colors.blue[900],
                    ),
                  );
                } else if (snapshot.hasError) {
                  return const Center(
                    child: Text("Something went wrong please try later"),
                  );
                } else if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: snapshot.data!.docs.length,
                      itemBuilder: (context, index) {
                        var friendId = snapshot.data!.docs[index].id;
                        var lastMessage = snapshot.data!.docs[index]['lastMessage'];
                        return FutureBuilder(
                          future: FirebaseFirestore.instance.collection('users').doc(friendId).get(),
                            builder: (BuildContext context , AsyncSnapshot snapshot) {
                            **final userModel = UserModel.fromMap(snapshot.data.data() as Map<String,dynamic>);**
                            if (snapshot.hasData) {
                              var friend = snapshot.data;
                              if (search.isEmpty) {
                                return ListTile(
                                  onTap: () {
                                    Navigator.push(context,
                                        MaterialPageRoute(builder: (context) =>
                                            ChatRoom(
                                                userModel: userModel,
                                                friendName: friend['name'],
                                                friendImage: friend['imageUrl'],
                                                friendId: friend['uid'],
                                                friendEmail: friend['email']
                                            ),
                                        ),
                                    );
                                  },
                                  title: Text(
                                    friend['name'],
                                    style: GoogleFonts.raleway(
                                        fontWeight: FontWeight.normal),
                                  ),
                                  subtitle: Text(lastMessage,
                                    overflow: TextOverflow.ellipsis,
                                    style: GoogleFonts.raleway(
                                        fontWeight: FontWeight.normal),
                                  ),
                                  leading: Container(
                                    height: 45,
                                    width: 45,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(15.0),
                                        color: Colors.white),
                                    child: const Center(
                                      child: Icon(Icons.person),
                                    ),
                                  ),
                                );
                              } else if (friend['name']
                                .toString()
                                .toLowerCase()
                                .startsWith(search.toLowerCase()) ||
                                friend['name']
                                    .toString()
                                    .toUpperCase()
                                    .startsWith(search.toUpperCase())) {
                              return ListTile(
                                onTap: () {
                                  Navigator.push(context,
                                    MaterialPageRoute(builder: (context) =>
                                        ChatRoom(
                                            userModel: userModel,
                                            friendName: friend['name'],
                                            friendImage: friend['imageUrl'],
                                            friendId: friend['uid'],
                                            friendEmail: friend['email']
                                        ),
                                    ),
                                  );
                                },
                                title: Text(
                                  friend['name'],
                                  style: GoogleFonts.raleway(
                                      fontWeight: FontWeight.normal),
                                ),
                                subtitle: Text(lastMessage,
                                  style: GoogleFonts.raleway(
                                      fontWeight: FontWeight.normal),
                                ),
                                leading: Container(
                                  height: 45,
                                  width: 45,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(15.0),
                                      color: Colors.white),
                                  child: const Center(
                                    child: Icon(Icons.person),
                                  ),
                                ),
                              );
                            }
                            return Container();
                            }
                            return Container();
                          }
                        );
                      });
                }
                return Container();
              },
            ),
          ),
        ],
      ),
    );
  }
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56

1 Answers1

0

Generate the model after getting data like

builder: (BuildContext context , AsyncSnapshot snapshot) {
    if (snapshot.hasData) {
      final mapData = snapshot.data.data() as Map?;
      if(mapData == null) return Text("Got null data");

      final userModel = UserModel.fromMap(mapData);
      var friend = snapshot.data;
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56