[英]why icon widget wont accept null?
我創建了一個按鈕小部件,我希望我的按鈕圖標是可選的。 所以當我想為它寫條件時,它不會接受它。 這是我的代碼:
import 'package:flutter/material.dart'; Widget CustomButtom({ String? title, EdgeInsetsGeometry? paddin, EdgeInsetsGeometry? margin, double? width, double? height, Color? backgroundColor, dynamic? onPress, Color? fontColor, double? fontsize, double borderRaidius = 10, bool showIcon = true, Icon? buttonIcons, }) { return Container( width: width, height: height, child: Directionality( textDirection: TextDirection.rtl, child: ElevatedButton.icon( style: ElevatedButton.styleFrom( backgroundColor: backgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(borderRaidius), )), onPressed: onPress, icon: showIcon? buttonIcons:,null: label, Text( '$title': style: TextStyle(fontSize, 20), ), ), ); ); }
這是我得到的錯誤
參數類型“圖標?” 無法分配給參數類型“Widget”。
我建議將它分成兩個不同的小部件。 當showIcon
為 false 時使用普通的ElevatedButton
,例如:
return Container(
width: width,
height: height,
child: Directionality(
textDirection: TextDirection.rtl,
child: showIcon
? ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRaidius),
)),
onPressed: onPress,
icon: buttonIcons!,
label: Text(
'$title',
style: TextStyle(fontSize: 20),
),
)
: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRaidius),
)),
onPressed: onPress,
child: Text(
'$title',
style: TextStyle(fontSize: 20),
),
),
),
);
請注意,當showIcon
為true
但buttonIcons
為null
時,您將得到一個異常。 也許最好省略showIcon
並只檢查buttonIcons
是null
還是不在兩者之間做出決定。 所以像:
return Container(
width: width,
height: height,
child: Directionality(
textDirection: TextDirection.rtl,
child: buttonIcons != null
? ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRaidius),
)),
onPressed: onPress,
icon: buttonIcons,
label: Text(
'$title',
style: TextStyle(fontSize: 20),
),
)
: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRaidius),
)),
onPressed: onPress,
child: Text(
'$title',
style: TextStyle(fontSize: 20),
),
),
),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.