Home > Software engineering >  display list objects in for loop table flutter
display list objects in for loop table flutter

Time:12-05

I added objects into my list, how do i for loop and print out the items in 2 types which are carType and sales, i only understand how to get from one value, but if 2 value with different field, i dont understand

var records = [{ crv, 800 }, { hrv, 400 }, { sedan, 1500 }]

children: [
                  for(var item in records)
                  Table(
                    children: [
                      TableRow(
                          children: [
                            Center(child: Text('${item}',style: TextStyle(fontFamily: 'MonSemi', fontSize: 17,color: Colors.white),)),
                           
                          ]
                      )
                    ],
                  )
                ],

CodePudding user response:

Here you go, please change the records to List<Map<String, dynamic>> instead of Set of object

   import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
   const MyHomePage({super.key, required this.title});
   final String title;


  @override
  State<MyHomePage> createState() => _MyHomePageState();
       
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
  List<Map<String, dynamic>> records = [
  {"crv": 800},
  {"hrv": 400},
  {"sedan": 1500}
  ];

return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Center(
      child: DataTable(
        horizontalMargin: 25,
        columns: const <DataColumn>[
          DataColumn(label: Text("Car Type"), numeric: false),
          DataColumn(label: Text("Sales"), numeric: true),
        ],
        rows: records
            .map((e) => DataRow(cells: [
                  DataCell(Text(e.entries.first.key)),
                  DataCell(Text(e.entries.first.value.toString())),
                ]))
            .toList(),
      ),
    ));
  }
 }

Screenshot: https://i.stack.imgur.com/eNjB5.png

  • Related