如何在 flutter 中使用具有空安全性的 showbottomsheet?

how to use showbottomsheet with null safety in flutter?

这周我还在学习 flutter new,好像课程已经过时了,所以每次遇到 null safety 错误时我都很挣扎。现在,我不能使用 showbottomsheet .. 试过空检查(!) 但是 onPressed() 总是返回 null ,我不知道我应该怎么做才能防止这种情况发生..

错误:方法'showBottomSheet'不能无条件调用因为接受者可以是'null'.

当我使用空检查时:它说“不能使用空操作数”

这是我使用的代码片段:

var scaffoldkey = GlobalKey<ScaffoldState>();


onPressed: () {
        scaffoldkey.currentState.showBottomSheet(
          (context) => Container(
            color: Colors.red,
            padding: EdgeInsets.all(
              20.0,
            ),
          ),
        );
      },

在错误代码前打上问号或感叹号即可:

var scaffoldkey = GlobalKey<ScaffoldState>();
onPressed: () {
        scaffoldkey.currentState?.showBottomSheet(
          (context) => Container(
            color: Colors.red,
            padding: EdgeInsets.all(
              20.0,
            ),
          ),
        );
      },

问题:currentState 可能为空。 如果你打一个问号,当它为空时它什么都不做,不调用 showBottomSheet 方法。

如果插入感叹词,它会强制调用 showBottomSheet 方法,即使它是 null,如果它是 null,它会像 null-aware 时代之前一样抛出错误。

试试下面的代码希望对你有帮助。只需单击其他,然后查看您的 result.refer 官方文档 here for bottomsheet

 ListTile(
    title: Text('Other '),
    trailing: Icon(Icons.arrow_forward_ios),
    onTap: () => bottomSheet(context),
  ),

您的 bottomSheet 函数:

bottomSheet(BuildContext context) {
    showModalBottomSheet(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(30),
        ),
      ),
      context: context,
      builder: (context) {
        return Container(
          height: 100,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            // mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    child: Icon(Icons.add),
                  ),
                  InkWell(
                    child: Icon(Icons.person),
                  ),
                  InkWell(
                    child: Icon(Icons.check),
                  ),
                  InkWell(
                    child: Icon(Icons.ac_unit),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

您的结果屏幕->