【问题标题】:Null check operator used on a null value - Flutter用于空值的空检查运算符 - Flutter
【发布时间】:2022-02-01 17:27:34
【问题描述】:

我正在尝试制作一个列出驱动器中文件的谷歌驱动器应用程序。但是我在空值错误上使用了空检查运算符。我知道发生了什么。但我无法解决。

 @override
  Widget build(BuildContext context) {
    return Scaffold(
         body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              onPressed: () {},
              child: Text('UPLOAD'),
            ),
            if (list != null)
              SizedBox(
                height: 300,
                width: double.infinity,
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: list!.files?.length,
                  itemBuilder: (context, index) {
                    final title = list!.files![index].originalFilename;
                    return ListTile(
                      leading: Text(title!),
                      trailing: ElevatedButton(
                        child: Text('Download'),
                        onPressed: () {
                        },
                      ),
                    );
                  },
                ),
              )
          ],
        ),
      ),
      floatingActionButton: Row(
        children: [
          FloatingActionButton(
            onPressed: _listGoogleDriveFiles,
            child: Icon(Icons.photo),
          ),
          FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        ],
      ),
    );
  }
}


当我运行它时,会显示上传文本,并且错误显示在文本下方。所以错误一定是由于列表为空。但我只想在列表不为空时才显示它。

怎么办?

【问题讨论】:

    标签: flutter dart google-drive-api dart-null-safety


    【解决方案1】:

    该错误意味着您在运行时恰好是null 的东西上使用了null 检查运算符(感叹号)。因此,查看您的代码,不仅可能是null 的列表,还有您用! 标记的其他对象。

    问题出在此处,除非我在您的代码中遗漏了一些 !

    itemCount: list!.files?.length,
    itemBuilder: (context, index) {
        final title = list!.files![index].originalFilename;
        return ListTile(
          leading: Text(title!),
          trailing: ElevatedButton(
            child: Text('Download'),
            onPressed: () {
              downloadGoogleDriveFile(
                  filename: list!.files![index].originalFilename,
                  id: list!.files![index].id);
            },
          ),
        );
    },
    

    为避免使用! 时遇到该错误,您可以显式检查对象是否为null,例如:

    if (list == null) {
       [...some error handling or a message with a warning]
    } else {
       [your original code where you can use ! without fear of errors]
    }
    

    或者您可以仅在对象为空的情况下为其赋值,如下所示:

    title??= ['Default title for when some loading failed or something'];
    

    【讨论】:

    • 这里需要注意的重要一点是,null itemCount 表示无限,而不是零。
    • 问题是原始文件名。谢谢你的回答。
    猜你喜欢
    • 2022-01-18
    • 2023-01-05
    • 2021-02-25
    • 2022-06-15
    • 2022-01-05
    • 2021-08-30
    • 2021-11-06
    • 2021-06-17
    • 2021-01-24
    相关资源
    最近更新 更多