【问题标题】:how to use showbottomsheet with null safety in flutter?如何在颤动中使用具有空安全性的showbottomsheet?
【发布时间】:2021-12-08 22:09:29
【问题描述】:

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

错误:无法无条件调用方法“showBottomSheet”,因为接收者可以为“null”。

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

这是我使用的一段代码:

var scaffoldkey = GlobalKey<ScaffoldState>();


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

【问题讨论】:

  • 简单使用:onPressed: () { showModalBottomSheet( context: context, builder: (BuildContext context) {

标签: flutter dart mobile dart-null-safety


【解决方案1】:

在错误代码前加一个问号或感叹词:

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

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

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

【讨论】:

    【解决方案2】:

    试试下面的代码希望它对你有帮助。只需单击其他并查看您的结果。请参阅官方文档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),
                      ),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      }
    

    您的结果屏幕->

    【讨论】:

    • @Nyctophilius 欢迎如果我的回答解决了您的问题,请接受并支持我的回答
    猜你喜欢
    • 2021-06-12
    • 2021-09-22
    • 2021-10-01
    • 2021-03-30
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多