Home > Software design >  Using the .map method on a list of constructors in flutter
Using the .map method on a list of constructors in flutter

Time:12-14

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()]

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()],
          )
        ],
      ),
    );
  }
}

CodePudding user response:

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.

  • Related