查询用户数据时对空值使用空检查运算符

Null check operator used on a null value while querying the User-Data

所以我正在创建一个聊天应用程序。我需要通过提及他们的用户名和电子邮件来显示 firebase 中所有用户的列表。 我在第 56 行收到上述错误。 此外,如果我删除行中的空检查运算符

QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;

而且一开始就晚替换会产生延迟初始化错误。

import 'package:chatapp/services/database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class Search extends StatefulWidget {
  _Search createState() => _Search();
}

class _Search extends State<Search> {
  QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
  bool isLoading = false;
  bool haveUserSearched = false;
  DatabaseMethods databaseMethods = new DatabaseMethods();
  var searchEditingController = TextEditingController();

  InitiateSearch() async {
    if (searchEditingController.text.isNotEmpty) {
      setState(() {
        isLoading = true;
      });
      await databaseMethods.GetUserByUsername(searchEditingController.text)
          .then((snapshot) {
        searchResultSnapshot = snapshot;
        print("$searchResultSnapshot");
        setState(() {
          isLoading = false;
          haveUserSearched = true;
        });
      });
    }
  }

  Widget UserList() {
    return Container(
      height: 500,
      child: ListView.builder(
          itemCount: searchResultSnapshot?.docs.length,
          itemBuilder: (context, index) {
            return UserTile(
              searchResultSnapshot?.docs[index].data()["userName"],
              searchResultSnapshot?.docs[index].data()["userEmail"],
            );
          }),
    );
  }

  Widget UserTile(String? userName, String? userEmail) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      child: Row(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                userName!,                                               //error here
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              Text(
                userEmail!,
                style: TextStyle(color: Colors.white, fontSize: 16),
              )
            ],
          ),
          Spacer(),
          GestureDetector(
            onTap: () {
              null;
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                  color: Colors.blue, borderRadius: BorderRadius.circular(24)),
              child: Text(
                "Message",
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          leading: Builder(
            builder: (BuildContext context) {
              return IconButton(
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                  });
            },
          ),
          title: Text('Search'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Column(
            children: [
              Container(
                height: 36,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                    ),
                    BoxShadow(
                      color: Colors.black,
                      spreadRadius: -12.0,
                      blurRadius: 12.0,
                    ),
                  ],
                ),
                margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
                child: Padding(
                  padding:
                      const EdgeInsets.symmetric(vertical: 0, horizontal: 10.0),
                  child: TextFormField(
                    style: TextStyle(color: Colors.black),
                    controller: searchEditingController,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Search',
                      hintStyle: TextStyle(color: Colors.grey),
                      icon: GestureDetector(
                        onTap: () {
                          InitiateSearch();
                        },
                        child: Icon(
                          Icons.search,
                          color: Colors.grey,
                        ),
                      ),
                      suffixIcon: IconButton(
                        onPressed: searchEditingController.clear,
                        icon: Icon(
                          Icons.cancel_rounded,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                ),
              ), //Search
              SizedBox(
                height: 12,
              ),
              UserList(),
            ],
          ),
        ));
  }
}

这是我的数据库文件。

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseMethods {
  GetUserByUsername(String username) async {
    return await
    FirebaseFirestore.instance
        .collection('users')
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        print(doc["userName"]);
      });
    });
  }

  Future<void> UploadUserInfo(userData) async {
    FirebaseFirestore.instance.collection("users").add(userData).catchError((e) {
      print(e.toString());
    });
  }
}

我真的很感激你的帮助。

代替

return UserTile(
          searchResultSnapshot?.docs[index].data()["userName"],
          searchResultSnapshot?.docs[index].data()["userEmail"],
        );

使用这个

return UserTile(
          searchResultSnapshot?.docs[index].data()["userName"]??"",
          searchResultSnapshot?.docs[index].data()["userEmail"]??"",
        );

并替换字符串?带有字符串(删除?)

Widget UserTile(String userName, String userEmail)

并使用如下值

Text(userName,style: TextStyle(color: Colors.white, fontSize: 16),),

你可以替换下面的一段代码

 children: [
              Text(
                userName!,                                               //error here
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              Text(
                userEmail!,
                style: TextStyle(color: Colors.white, fontSize: 16),
              )
            ],

 children: [
              Text(
                userName ?? "",                                               //error here
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              Text(
                userEmail ?? "",
                style: TextStyle(color: Colors.white, fontSize: 16),
              )
            ],