[英]The parameter 'colour' can't have a value of 'null' because of its type, but the implicit default value is '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 中構造函數的工作方式存在一些差異。
@required
現在只是required
的 - 不再有 @ 符號。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
正如之前的回答中所說:
在你的情況下,也許我會使用這樣的東西:
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.