0

您好,当我尝试运行代码时出现此错误

lib/layout/home_layout.dart:54:36: Error: Method 'showBottomSheet' cannot be called on 'ScaffoldState?' because it is potentially null.
 - 'ScaffoldState' is from 'package:flutter/src/material/scaffold.dart' ('/C:/src/flutter/packages/flutter/lib/src/material/scaffold.dart').
Try calling using ?. instead.
          scaffoldKey.currentState.showBottomSheet(
                                   ^^^^^^^^^^^^^^^

我有一个已定义的变量:

 var scaffoldKey = GlobalKey<ScaffoldState>();

在这里,我试图在单击浮动操作按钮时构建一个底页

floatingActionButton: FloatingActionButton(
    onPressed: () {
      scaffoldKey.currentState.showBottomSheet(
              (context) => Container(
                width: double.infinity,
                height: 120.0,
                color: Colors.red
              ),
      );
    },
    child: const Icon(
        Icons.add
    ),
  ),

请问,有人能告诉我哪里出错了吗?

4

1 回答 1

1

所以问题是,正如您可能已经发现的那样,flutter 不知道当前状态变量是否为 null,在某些情况下它为 null,因此,它不会让您调用它,这是明显的解决方案:

if (scaffoldKey.currentState != null) {
  scaffoldKey.currentState!.showBottomSheet(...);
}

注意!after currentState,当你放在!一个可能为 null 的值之后时,你是在告诉颤振,“相信我,这个值不为 null”,这意味着如果它为 null,它会抛出一个错误,但否则它不会抱怨。

A,也许更好的解决方案是按照您的错误代码的建议进行操作:

不能在“ScaffoldState”上调用方法“showBottomSheet”?因为它可能为空。尝试使用? 调用。反而。脚手架Key.currentState.showBottomSheet(

像这样:

scaffoldKey.currentState?.showBottomSheet(...);

使用时,?.您有条件地调用可能为空值的方法或成员变量

所以上面那行说的是,“如果currentState不为空,调用它的showBottomSheet方法,否则,什么都不做”。

于 2021-11-20T02:53:43.377 回答