Home > database >  Build a table row in Flutter
Build a table row in Flutter

Time:01-30

I have data that comes from API and I want to arrange it in the form of a table as in the image attached below, but when I do that the data is repeated and I could not solve the problem, I need help on modifying the code below so that I do not want to repeat the code until the modification begins.

Clarification

enter image description here

The code

class StarringComponent extends StatelessWidget {
  StarringComponent({Key? key}) : super(key: key);

  final List<_StarringModel> _listOfStarring = [
    _StarringModel('Michael J. Fox', 'https://www.biography.com/.image/ar_8:10,c_fill,cs_srgb,fl_progressive,g_faces:center,q_auto:good,w_620/MTkwNTAwODA4ODM0NDI2Nzc4/gettyimages-1144626740.jpg'),
    _StarringModel('Christopher Lloyd', 'https://s3.r29static.com/bin/entry/9e6/0,0,2000,2000/x,80/2172764/image.jpg'),
    _StarringModel('Robert Zimek', 'https://media1.popsugar-assets.com/files/thumbor/XS_IeHJo2d3MzS-0CXmqOZ0Zl34/fit-in/2048xorig/filters:format_auto-!!-:strip_icc-!!-/2019/01/08/515/n/1922398/7f748b5fb07a03fd_GettyImages-1019711520/i/Charlie-Hunnam.jpg'),
    _StarringModel('Lea Thompson', 'https://www.independent.ie/migration_catalog/8bb89/25195674.ece/AUTOCROP/w620/N0217211295348219998A_1'),
  ];

  @override
  Widget build(BuildContext context) {
    return Table(children: List.generate(_listOfStarring.length, (index) => _buildTableRow(context, _listOfStarring[index].name, _listOfStarring[index].image)));
  }

  TableRow _buildTableRow(BuildContext context, String name, String image) {
    return TableRow(
      children: List.generate(2, (index) => Padding(
        padding: EdgeInsets.symmetric(vertical: 10),
        child: Row(
          children: [
            CircleAvatar(
              radius: 14,
              backgroundColor: Colors.red.withOpacity(0.4),
              backgroundImage: NetworkImage(image),
            ),
            SizedBox(width: 10),
            Flexible(
              child: Text(name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  ),
            ),
          ],
        ),
      ))
    );
  }
}

Starring model

class _StarringModel {
  String name, image;

  _StarringModel(this.name, this.image);
}

CodePudding user response:

Use GridView for simpler implementation.

GridView.builder(
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
...
  ),
  itemCount: _listOfStarring.length,
  itemBuilder: (BuildContext ctx, index) {
    return _buildItem(
      _listOfStarring[index].name,
      _listOfStarring[index].image,
    );
  },
);

Widget _buildItem(String name, String image) {
...
}

  • Related