【问题标题】:The parameter 'text', 'onPressed', 'outlineBtn' can't have a value of 'null' because of its type, but the implicit default value is 'null'参数 'text', 'onPressed', 'outlineBtn' 不能有值 'null' 因为它的类型,但是隐含的默认值是 'null'
【发布时间】:2021-09-05 09:34:24
【问题描述】:

代码显示错误,即所有文本参数,onPressed,outlineBtn 不能具有 null 值,当我在它们之前使用 require 关键字时,此问题得到解决,但随后开始显示此错误。

错误:

正在运行 Gradle 任务“assembleDebug”... lib/Widget/custom_btn.dart:12:24:警告:null-aware 操作的操作数 '??'具有不包括空值的“布尔”类型。 bool _outlineBtn = outlineBtn ??错误的; ^ lib/Widget/custom_btn.dart:33:11:警告:null-aware 操作的操作数 '??'具有不包括空值的“字符串”类型。 文本 ?? “文字”,

这是我的代码:

import 'package:flutter/material.dart';

class CustomBtn extends StatelessWidget {
final String text;
final Function onPressed;
final bool outlineBtn;
CustomBtn(
  {required this.text, required this.onPressed, required this.outlineBtn});

@override
Widget build(BuildContext context) {
bool _outlineBtn = outlineBtn ?? false;

return GestureDetector(
  onTap: onPressed(),
  child: Container(
    height: 60.0,
    alignment: Alignment.center,
    decoration: BoxDecoration(
      color: _outlineBtn ? Colors.transparent : Colors.black,
      border: Border.all(
        color: Colors.black,
        width: 2.0,
      ),
      borderRadius: BorderRadius.circular(12.0),
    ),
    margin: EdgeInsets.symmetric(
      horizontal: 24.0,
      vertical: 24.0,
    ),
    child: Text(
      //Create New Account
      text ?? "Text",
      style: TextStyle(
        fontSize: 16.0,
        fontWeight: FontWeight.w600,
        color: _outlineBtn ? Colors.black : Colors.white,
      ),
    ),
  ),
);

} }

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies dart-pub


    【解决方案1】:

    发生这种情况是因为required 关键字表示必须提供变量并且它不能为空。在您的情况下,outlineBtn 永远不能为空。

    bool _outlineBtn = outlineBtn ?? false;
    

    要解决此问题,您可以省略空检查或省略 required 关键字并将变量更改为可为空。

    final String? text;
    final Function? onPressed;
    final bool? outlineBtn;
    

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2021-10-28
      • 2021-11-12
      • 2022-01-03
      • 2022-01-20
      • 1970-01-01
      • 2022-06-14
      • 2022-08-13
      • 2021-08-19
      相关资源
      最近更新 更多