i created a button widget and i want the icon of my button to be optional. so when i wanna write condition for it ,it wont accept it. here is my code:
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), ), ), ), ); }
and this is the error im getting
The argument type 'Icon?' can't be assigned to the parameter type 'Widget'.
CodePudding user response:
I'd suggest splitting it up to two different widgets then. Use a normal ElevatedButton
when there's showIcon
false, like:
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),
),
),
),
);
Note that you will get an exception when you have showIcon
as true
but buttonIcons
as null
. Maybe it's better to leave out the showIcon
and just check on buttonIcons
being null
or not to decide between the two. So like:
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),
),
),
),
);