Erik Kammerfors
Erik Kammerfors

Reputation: 25

How can I use methods to replace duplicate flutter code?

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),

Upvotes: 0

Views: 195

Answers (3)

Danusha Malshan
Danusha Malshan

Reputation: 39

1.click your duplicated widget and click the yellow bulb icon and select Extract Widget 2.give a proper name for your custom widget 3.then set parameters correctly and use it

Row(
         mainAxisAlignment: MainAxisAlignment.center,
         children: [
        _CustomCard(
          imagePressed: 'assets/pressed/${foodItems[0].imageSource}Pressed.png',
                   
                       imageNotPressed: 'assets/notPressed/${foodItems[0].imageSource}.png',),
          SizedBox(width: 20),

         _CustomCard(imagePressed: 'assets/pressed/${foodItems[1].imageSource}Pressed.png',
                       imageNotPressed: 'assets/notPressed/${foodItems[1].imageSource}.png',),
        
        ],
      ),



    class _CustomCard extends StatelessWidget {
  const _CustomCard({
    Key? key, required this.imagePressed, required this.imageNotPressed,
  }) : super(key: key);
  
  final String imagePressed;
  final String imageNotPressed;
  @override
  Widget build(BuildContext context) {
    return 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(imagePressed!)
              : Image.asset(imageNotPressed!)
          ),
          iconSize: 115,
      ),
        );
  }
}

Upvotes: 0

Aimen SAYOUD
Aimen SAYOUD

Reputation: 365

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

Upvotes: 1

aedemirsen
aedemirsen

Reputation: 142

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: .....
   );
}

Upvotes: 1

Related Questions