For a learning I have created a list of Map ..I want to sum all of the key's value except month number like...in short I want to make loop for key's value
for seeing output.i have taken list tile where title should show some of expenses and leading shows month number
{
'Month':1,
'Lightbill':305,
'Provisional':503,
}
Now I want like this
1 808
here is my basic code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
List<Map<String,int>> mylist=[
{
'Month':1,
'Provisional': 4500,
'Teaexp': 980,
'Lightbill': 1240,
'Assets': 399,
},
{ 'Month':2,
'Provisional': 0250,
'Teaexp': 150,
'Lightbill': 240,
'Assets': 30,
}
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
children: List.generate(mylist.length, (index) {
int sum=0;
sum=sum int.parse(mylist[index]['Provisional'].toString());
return Container(
child: ListTile(
leading:CircleAvatar(child:
Text(mylist[index]['Month'].toString()),),
title: Text(sum.toString()),
),
);
}),
),
),
),
);
}
}
CodePudding user response:
i am assuming all the map value are non null and has type int. you can achieve like it -
Text(
"${(mylist[index]["Lightbill"] as int) (mylist[index]["Provisional"] as int) (mylist[index]["Teaexp"] as int)}"
)
CodePudding user response:
You can get all values like myMap.values
and to skip 1st I am using .skip()
and then to sum up using reduce
.
final sum = mylist[index]
.values
.skip(1)
.reduce((value, element) => value element);
CodePudding user response:
You could use this:
Text((mylist[index].values.sum - mylist[index]['Month']!).toString())
This needs
import 'package:collection/collection.dart';
to use sum
CodePudding user response:
Yet another way to do it would be to use the keys
property to retrieve a list of all keys and filter it:
int sum(Map<String, int> input) {
int sum = 0;
input
.keys
.where((String key) => key != 'Month')
.forEach((String key) => sum = input[key]);
return sum;
}