My problem is, I am getting "null check operator used on a null value" error. As you know, it is darts default null check error.
And I am getting this error on default parameter. So It can't be possible but why I am getting this error ?
for quick search: "buttonColor??backgroundColor!" -> this line. Background color has a optional value.
All my code is below. Thank you a lot :)
class FormButtons extends GestureDetector {
FormButtons.textButton({
Key? key,
required String buttonText,
required FutureOr<void> Function()? onTap,
Color? borderColor,
Color? backgroundColor,
Color? textColor=const FormColors.black3()
}) : super(
key: key,
onTap: onTap,
child: _formButtonFrame(
borderColor: borderColor,
backgroundColor: backgroundColor,
child: _formButtonText(buttonText, textColor!)
)
);
}
Container _formButtonFrame({
required Widget child,
Color? buttonColor,
Color? borderColor=Colors.transparent,
Color? backgroundColor=Colors.transparent
}){
print(backgroundColor==null);
print((backgroundColor??backgroundColor)==null);
print("x");
print((backgroundColor??backgroundColor)==null);
print((backgroundColor??backgroundColor)==Colors.transparent);
print("_formButtonFrame");
return Container(
padding: FormEdgeInsets.formButtonsPadding(),
decoration: BoxDecoration(
color: buttonColor??backgroundColor!,
boxShadow: [
BoxShadow(color: borderColor!, spreadRadius: 1.0.sp),
]
),
child: child,
);
}
And console output is like;
I/flutter (12737): true
I/flutter (12737): true
I/flutter (12737): x
I/flutter (12737): true
I/flutter (12737): false
I/flutter (12737): _formButtonFrame
And I am just calling this widget
Widget get _defaultTextButton=>FormButtons.textButton(
buttonText: "Default Text Button",
onTap: ()=>print("_defaultTextButton")
);
CodePudding user response:
When you write:
Container _formButtonFrame({
...
Color? backgroundColor=Colors.transparent
}){
you are specifying a default argument to use if the caller omits the argument entirely. However, because backgroundColor uses a nullable type, the caller can still explicitly pass a null argument:
_formButtonFrame(
...
backgroundColor: null,
...,
)
which is effectively what happens in the FormButtons.textButton constructor where it forwards its own backgroundColor argument.
If you don't want backgroundColor to ever be null, don't make it nullable. (This will require fixing all callers, however, and it also will make it harder for callers to forward arguments.)
If you instead want null to use the Colors.transparent default, you can move the default value into the function body:
Container _formButtonFrame({
...
Color? backgroundColor,
}) {
backgroundColor ??= Colors.transparent;
