【问题标题】:Flutter ,dart,The parameter 'colour' can't have a value of 'null' because of its type, but the implicit default value is 'null'Flutter ,dart,参数 'colour' 因为它的类型不能有 'null' 的值,但是隐含的默认值是 'null'
【发布时间】:2022-06-14 04:59:36
【问题描述】:

我不知道为什么我会收到错误,我以前编写过相同的代码,它工作得非常好,也许一些新的更新或插件请帮我解决我的错误

import 'package:flutter/material.dart';

class RoundedButton extends StatelessWidget {
  final String title;
  final Color colour;
  final Function onPressed;
  RoundedButton({this.title, this.colour, @required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        elevation: 5.0,
        color: colour,
        borderRadius: BorderRadius.circular(30.0),
        child: MaterialButton(
          onPressed: onPressed,
          minWidth: 200.0,
          height: 42.0,
          child: Text(
            title,
            style: TextStyle(color: Colors.white),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    您已将 Dart SDK 更新到支持 null-safety 的版本。对于 null 安全性,Dart 中构造函数的工作方式会有所不同。

    1. @required 现在只是 required - 不再有 @ 符号。
    2. 如果不需要属性,则它必须具有默认值,或者必须具有可为空的类型,例如String?Color?

    使用默认值,您的代码可能如下所示:

    final String title;
    final Color colour;
    final void Function() onPressed;
    
    RoundedButton({
        this.title = "",
        this.colour = Colors.blue,
        required this.onPressed,
    });
    

    你班上的其他人都是一样的。


    另一方面,如果您将属性设为可为空,您可能会得到如下结果:

    final String? title;
    final Color? colour;
    final void Function() onPressed;
    
    RoundedButton({
        this.title,
        this.colour,
        required this.onPressed,
    });
    

    现在,对于colour 属性,您无需更改任何内容,因为Material.color 可以为空。但是,由于 Text 需要不可为空的 String,因此您必须更改传递 title 属性的方式:

    Text(
        title ?? "", // If title is null, use an empty string
        // ...
    )
    

    child: title == null // Only build the Text widget if title is not null
        ? null 
        : Text(
              title,
              // ...
          )
    

    在此处深入阅读 null 安全性:https://dart.dev/null-safety/understanding-null-safety

    【讨论】:

      【解决方案2】:

      正如之前的回答中所说:

      1. 更改@required => 必需
      2. '?' 添加到可能为空的变量中
      3. 添加默认

      在你的情况下,也许我会使用这样的东西:

      final String title;
      final Color colour;
      final VoidCallBack? onPressed;
      
      RoundedButton({
          required this.title,
          this.colour = Colors.blue,
          this.onPressed,
      });
      

      因为标题不能为空,所以颜色可以是默认的,onPress 可以为空,以备将来实现您的应用。

      【讨论】:

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