简体   繁体   English

如何在 flutter 中将 Gridview 转换为 Listview?

[英]how to transform Gridview into Listview in flutter?

i would like to transform a GridView into a Listview, here is the Gridview code:我想将 GridView 转换为 Listview,这是 Gridview 代码:

在此处输入图像描述

and here is what i tried to do:这是我试图做的:

      return ListView.builder(
 itemBuilder: (context,index){
     _buildGridCards(context); 
   }

   );
  }

    List<dynamic> _buildGridCards(BuildContext context) {
   if (widget.productsToDisplay == null || widget.productsToDisplay.isEmpty) {
    return const <Card>[];
     }
   final ThemeData theme = Theme.of(context);
    return widget.productsToDisplay.map((product) {
    Uint8List img64;
    try {
    img64 = base64Decode(product.image);
    } catch (e) {
    print(e);
    }

  return Card(
    clipBehavior: Clip.antiAlias,
    child: InkWell(
      onTap: () {
        Navigator.push(
          context,
             ...

when i executed the code, nothing appeared当我执行代码时,什么都没有出现

I believe you forgot itemCount , so the final will be我相信你忘记了itemCount ,所以最终将是

return ListView.builder(
  itemCount: 3, // the data length of your list view
 itemBuilder: (context,index){
     _buildGridCards(context); 
   }

You may also check the flutter doc.您还可以查看flutter 文档。 I hope it helps.我希望它有所帮助。

the item builder requires you to return a widget of which it will render the widget in the list at a defined index...项目构建器要求您返回一个小部件,它将在列表中以定义的索引呈现小部件...

you could keep calling the function _buildGridCards for each time the builder executes and have the following...每次构建器执行时,您都可以继续调用 function _buildGridCards并具有以下...

return ListView.builder(
  // Not forgetting to add the length ofcourse
  itemCount: _buildGridCards(context).length,
  itemBuilder: (context,index){
    return _buildGridCards(context)[index]; 
  }
);

or you could keep the list somewhere and only execute the function once like down here...或者您可以将列表保存在某处,并且只执行 function 就像在这里一样......


@Override
Widget build(BuildContext context) {
  List<Card> cards = _buildGridCards(context);

  return ListView.builder(
    // Not forgetting the length ofcourse
    itemCount: cards.length,
    itemBuilder: (context,index){
      return cards[index]; 
    }
  );
}

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM