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.
CodePudding user response:
The constructor of GridViewSelection
requires List?
for names and images but you are trying to supply one element. In order to fix this, you will have to extract a list of name
and image
each, from your list oldMenu
and then supply it to the constructor.
Revised code:
GridViewSelection(
menuList: oldMenu.length,
imageList: oldMenu.map((element) => element.image).toList(),
nameList: oldMenu.map((element) => element.name).toList(),
onTap: (){}),
Hope it helps!
CodePudding user response:
Make sure that you're returning your widget inside itemBuilder of a list to be given the index to use it.