Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using the .map method on a list of constructors in flutter

I have a class for transactions with a constructor. Using the constructor method, I created a list of transaction, with the aim of looping through these transactions and displaying it’s contents in a card but I’m getting errors while trying to use the .map method on the list.

The error message i’m getting is The element type ‘List<Map<dynamic, dynamic>>’ can’t be assigned to the list type ‘Widget’.

I have the error on [transactions.map((transaction) => {}).toList()]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the code:

class Hompage extends StatelessWidget {
  final List<Transaction> transactions = [
    Transaction(
      id: 't1',
      title: 'First Transaction',
      amount: 1000,
      date: DateTime.now(),
    ),
    Transaction(
      id: 't2',
      title: 'Second Transaction',
      amount: 500,
      date: DateTime.now(),
    )
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Event Planner'),
      ),
      body: Column(
        // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        // crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            width: double.infinity,
            child: Card(
              color: Colors.blue,
              child: Text('CHART'),
            ),
          ),
          Column(
            // children: [
            //   (transactions as List<Map<dynamic, dynamic>>)
            //       .map((transaction) => {})
            //       .toList()
            // ],

            children: [transactions.map((transaction) => {}).toList()],
          )
        ],
      ),
    );
  }
}

>Solution :

children: [transactions.map((transaction) => {}).toList()]

First, remove the brackets, you now have a list of lists:

children: transactions.map((transaction) => {}).toList()

Okay, better, but since children expects Widget type elements, you cannot just map to nothing.

children: transactions.map((transaction) => Text(transaction.title)).toList()

A lot better. You may want to find something fancier than a simple Text though.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading