gpt4 book ai didi

flutter - 无法将类型 'bool?' 的值分配给类型 'bool' 的变量,因为 'bool?' 可以为 null,而 'bool' 则不能

转载 作者:行者123 更新时间:2023-12-03 08:18:44 27 4
gpt4 key购买 nike

这是我的完整代码...

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: Error: A value of type 'bool?' can't be assigned to a variable of type 'bool' because 'bool?' is nullable and 'bool' isn't.if (Get.isDialogOpen) Get.back();

如果条件 Get.isDialogOpen,我在线路上遇到错误

最佳答案

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

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

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

关于flutter - 无法将类型 'bool?' 的值分配给类型 'bool' 的变量,因为 'bool?' 可以为 null,而 'bool' 则不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68527461/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com