簡體   English   中英

Flutter ,dart,參數 'colour' 因為它的類型不能有 'null' 的值,但是隱含的默認值是 'null'

[英]Flutter ,dart,The parameter 'colour' can't have a value of 'null' because of its type, but the implicit default value is 'null'

我不知道為什么我會收到錯誤,我以前編寫過相同的代碼並且它工作得非常好也許一些新的更新或插件請幫我解決我的錯誤

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),
          ),
        ),
      ),
    );
  }
}

在此處輸入圖像描述

您已將 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

正如之前的回答中所說:

  1. 更改@required =>必需
  2. 添加“?” 到可能為空的變量
  3. 添加默認

在你的情況下,也許我會使用這樣的東西:

final String title;
final Color colour;
final VoidCallBack? onPressed;

RoundedButton({
    required this.title,
    this.colour = Colors.blue,
    this.onPressed,
});

因為標題不能為空,所以顏色可以是默認顏色,onPress 可以為空,以便將來實現您的應用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM