LateInitializationError:字段尚未在 Flutter 中初始化

Posted

技术标签:

【中文标题】LateInitializationError:字段尚未在 Flutter 中初始化【英文标题】:LateInitializationError: Field has not been initialized in Flutter 【发布时间】:2021-11-17 09:44:01 【问题描述】:

我对 Flutter 相当陌生,我要在 Flutter 上构建一个 Messenger Chap 应用程序,我面临“LateInitilization:字段'searchSnapShot'尚未初始化的问题。以下是代码的 sn-p导致问题:

Widget searchList() 
return searchSnapShot != null ? ListView.builder(
  itemCount: searchSnapShot.docs.length,
    shrinkWrap: true,
    itemBuilder: (context, index) 
      return SearchTile(
          userName: searchSnapShot.docs[index].data()["name"],
          userEmail: searchSnapShot.docs[index].data()["email"],
      );
    
) : Container();

这个 sn-p 应该做的是返回与搜索查询匹配的用户列表。以下是整个 search.dart 的代码:

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

class SearchScreen extends StatefulWidget 

  @override
  _SearchScreenState createState() => _SearchScreenState();


class _SearchScreenState extends State<SearchScreen> 

  DatabaseMethods databaseMethods = new DatabaseMethods();
  TextEditingController searchTextEditingController = new TextEditingController();

  late QuerySnapshot <Map<String, dynamic>> searchSnapShot;

  initiateSearch() async 
    await databaseMethods
        .getUserByUsername(searchTextEditingController.text)
        .then((val) 
          setState(() 
              searchSnapShot = val;
          );
    );

  

  Widget searchList() 
    return searchSnapShot != null ? ListView.builder(
      itemCount: searchSnapShot.docs.length,
        shrinkWrap: true,
        itemBuilder: (context, index) 
          return SearchTile(
              userName: searchSnapShot.docs[index].data()["name"],
              userEmail: searchSnapShot.docs[index].data()["email"],
          );
        
    ) : Container();
  

  @override
  void initState() 
    super.initState();
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: appBarMain(context),
      body: Container(
        child: Column(
          children: [
            Container(
              color: Color(0xffFFC200),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
              child: Row(
                children: [
                  Expanded(
                      child: TextField(
                        controller: searchTextEditingController,
                        decoration: InputDecoration(
                          hintText: "search username..",
                            hintStyle: TextStyle(
                              color: Colors.black,
                            ),
                          border: InputBorder.none,
                        ),
                      )
                  ),
                  GestureDetector(
                    onTap: () 
                       initiateSearch();
                      ,
                    child: Container(
                        height: 30,
                        child: Image.asset("assets/images/search_white.png")),
                  ),
                ],
              ),
            ),
            searchList()
          ],
        ),
      ),
    );
  


class SearchTile extends StatelessWidget 

  late final String userName;
  late final String userEmail;

  SearchTile(required this.userName, required this.userEmail);

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Row(
        children: [
          Column(
            children: [
              Text(
                userName,
                style: simpleTextStyle()
              ),
              Text(
                userEmail,
                style: simpleTextStyle(),
              ),
            ],
          ),
          Spacer(),
          Container(
            decoration: BoxDecoration(
              color: Colors.amber,
              borderRadius: BorderRadius.circular(40)
            ),
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Text("Message"),
          )
        ],
      ),
    );
  

android Studio 中的错误描述:

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

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

【问题讨论】:

【参考方案1】:

当您使用late 时,这意味着变量可以被延迟初始化,因此,在某处使用它之前,您需要初始化,因此您无法对其进行空检查,如果您想对其进行空检查,请尝试@ 987654322@ 使该变量可以为空。

所以删除late并添加?

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

【讨论】:

非常感谢伙计,完成了这项工作。还必须对“文档”进行空检查。【参考方案2】:

请试试这个

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

【讨论】:

我之前尝试过这样做,给了我 9-10 个错误,包括“函数需要一个主体”、“必须使用关键字 'const'、'final'、'var' 或 a输入名称。”【参考方案3】:

使用以下方法初始化 searchSnapshot:

QuerySnapshot<dynamic>? searchSnapshot;

另外,在 searchTitle 中添加空检查:

SearchTitle(
      userName: searchSnapshot!.docs[index].data()['name'],
      userEmail: searchSnapshot!.docs[index].data()['email'],
  );SearchTitle(
      userName: searchSnapshot!.docs[index].data()['name'],
      userEmail: searchSnapshot!.docs[index].data()['email'],
  );

【讨论】:

以上是关于LateInitializationError:字段尚未在 Flutter 中初始化的主要内容,如果未能解决你的问题,请参考以下文章

LateInitializationError:字段“_userData@32329253”尚未初始化

LateInitializationError:字段尚未在 Flutter 中初始化

LateInitializationError:字段“chatRoomsStream”尚未在 Flutter 中初始化

如何解决 Flutter 中的 LateInitializationError?

LateInitializationError:字段“显示名称”尚未在 Flutter 共享首选项中初始化?

即使我在 initState 中初始化变量,Dart 也会抛出 LateInitializationError