【问题标题】:A value of type 'bool?' can't be assigned to a variable of type 'bool' because 'bool?' is nullable and 'bool' isn't'bool?' 类型的值不能分配给“bool”类型的变量,因为“bool?”可以为空,并且 'bool' 不是
【发布时间】:2021-10-02 06:00:59
【问题描述】:

这是我的完整代码...

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,我在行上遇到错误

【问题讨论】:

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


    【解决方案1】:

    您收到该错误是因为 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,并且最终返回 null,您的代码将在运行时崩溃。为避免这种情况,您可以告诉编译器仅在 isDialogOpen 已初始化时才调用它。即

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 2021-04-07
      • 2021-10-16
      相关资源
      最近更新 更多