I've created a program where I display 6 boxes (3 rows, 2 boxes on each row). This leads to alot of duplicate code that could (in normal Java) easily be refactored to a method instead where I send the index for each item.
It would have been nice to have a void method that's called with the index for foodItems and then creates everything. Or how should I do it?
Below is code for only one row, which basically looks the same for all rows except different indexes for the foodItem list.
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
child: IconButton(
onPressed: () {
setState(() {
buttonPressed(0);
});
},
padding: EdgeInsets.all(0.0),
icon: (getPressedState(0)
? Image.asset('assets/pressed/${foodItems[0].imageSource}Pressed.png')
: Image.asset('assets/notPressed/${foodItems[0].imageSource}.png')
),
iconSize: 115,
),
),
SizedBox(width: 20),
Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
child: IconButton(
onPressed: () {
setState(() {
buttonPressed(1);
});
},
padding: EdgeInsets.all(0.0),
icon: (getPressedState(1)
? Image.asset('assets/pressed/${foodItems[1].imageSource}Pressed.png')
: Image.asset('assets/notPressed/${foodItems[1].imageSource}.png')
),
iconSize: 115,
),
),
],
),
SizedBox(height: 20),
CodePudding user response:
simple create methods in your class, outside of build method:
@override
Widget build(BuildContext context) {
return Row(
_card([imagePath]),
SizedBox(width: 20),
_card([imagePath]),
);
}
Widget _card(String imagePath){
return Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
child: .....
);
}
CodePudding user response:
to avoid this duplication you should either create a method and pass the index as parameters or create a new widget in another class and pass the index also as a parameter to it