'bool?' 类型的值不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是

时间:2021-07-26 09:25:28

标签: flutter dart get flutter-getx flutter-get

这是我的完整代码...

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class DialogHelper{
  //show error dialog
 static void showErrorDialog({String title='error',String description='Something went wrong'})
  {
    Get.dialog(
      Dialog(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(title,style: Get.textTheme.headline4,),
              Text(description,style: Get.textTheme.headline6,),
              ElevatedButton(onPressed: () {
                if (Get.isDialogOpen) Get.back();
              },
                  child: Text('okay')),
            ],
          ),
        ),
      ),
    );

  }
}

我遇到了这个错误

<块引用>

19:25:错误:“bool”类型的值?不能分配给类型为 'bool' 的变量,因为 'bool?'可以为空,而 'bool' 不是。 if (Get.isDialogOpen) Get.back();

如果条件为 Get.isDialogOpen,我在线上出错

1 个答案:

答案 0 :(得分:2)

您收到该错误是因为 getter isDialogOpen 返回一个 Optional。这意味着返回值可以是 truefalsenull。但是,由于 if 条件只能与布尔值一起使用,因此 SDK 会告诉您如果 isDialogOpen 返回 null 会出现错误。

所以要解决这个问题,要么告诉编译器你确信你的 getter 永远不会返回空值,要么你必须给出一个默认值,以防从 .isDialogOpen 返回空值。我们分别这样做;

1-

  Get.isDialogOpen! \\ this means you are sure a null can't be returned

2-

 Get.isDialogOpen ?? false \\ this means incase a null is returned use false   

注意:如果您使用数字 1,并且最终返回空值,您的代码将在运行时崩溃。为避免这种情况,您可以告诉编译器仅在 isDialogOpen 已初始化时调用它。即

Get?.isDialogOpen ?? false \\If isDialogOpen is not initialized, false will be used