I made a custom MyMenu widget containing: title, imageUrl, shape, and page. The logic is that if there is no image available, an icon should be the default.
class MyMenu extends StatelessWidget {
MyMenu({this.title, this.icon, this.shape, this.page, this.imageUrl = ''}) {
if (icon != null) {
assert(imageUrl == null || imageUrl.isEmpty);
} else if (imageUrl != null && imageUrl.isEmpty) {
assert(icon == null);
}
}
final page;
final String title;
final IconData icon;
final String imageUrl;
final MaterialColor shape;
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(9.0),
child: InkWell(
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => page),
),
splashColor: Colors.amberAccent,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Visibility(
visible: icon != null && imageUrl.isEmpty,
child: Icon(
icon,
size: 80.0,
color: shape,
),
replacement: Image.asset(
imageUrl,
width: 80,
height: 80,
),
),
Expanded(child: Text(title, style: new TextStyle(fontSize: 17.0)))
],
),
),
),
);
}
}
class Menus extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: GridView.count(
crossAxisCount: 3,
children: <Widget>[
MyMenu(
title: "Sony",
imageUrl: 'assets/images/sony.png',
shape: Colors.brown,
page: SonyPage(),
),
MyMenu(
title: "Panasonic",
imageUrl: 'assets/images/panasonic.png',
shape: Colors.grey,
page: PanasonicPage2(),
),
],
),
);
}
}
Error: The parameter 'title, icon & shape' can't have a value of 'null' because of its type, but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier. When I add 'required', then I get a problem with the icon as it is not actually required in the 'Menus' class.
- When I add default values, other problems start coming up. I need help with a better way to do this. Thanks.