I have a gridview widget but I want to make it re usable so I can reuse it in many places without writing it again and again.
I have write it but I am facing one issue,
here is the widget i have written,
class GridViewSelection extends StatelessWidget {
GridViewSelection(
{super.key,
required this.menuList,
required this.onTap,
this.imageList,
this.nameList,});
VoidCallback onTap;
int menuList;
List? imageList;
List? nameList;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(15),
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, mainAxisSpacing: 10, crossAxisSpacing: 10),
itemCount: menuList,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: onTap,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SvgPicture.asset(
imageList![index],
fit: BoxFit.contain,
width: MediaQuery.of(context).size.width * 0.15,
),
const SizedBox(
height: 10,
),
Text(
textAlign: TextAlign.center,
nameList![index],
style: TextStyle(
fontSize: 14,
color: AppTheme.colors.greyFontColor),
),
]),
),
),
);
}));
}
}
the issue i am facing is, I have a list in which i have defined the name and image for the grid view. the problem is, how will i use that list. this is how I am reusing the widget but it throws an error.
GridViewSelection(
menuList: oldMenu.length,
imageList: oldMenu,
nameList: oldMenu,
onTap: (){}),
I can not use it like this but its says that [index] is not defined for the list.
GridViewSelection(
menuList: oldMenu.length,
imageList: oldMenu[index].image,
nameList: oldMenu[index].name,
onTap: (){}),
any help is highly appreciated.
2
Answers
The constructor of
GridViewSelection
requiresList?
for names and images but you are trying to supply one element. In order to fix this, you will have to extract a list ofname
andimage
each, from your listoldMenu
and then supply it to the constructor.Revised code:
Hope it helps!
Make sure that you’re returning your widget inside itemBuilder of a list to be given the index to use it.