Darshana
Darshana

Reputation: 650

How to create dynamic variables and assign list of data to it using flutter

How to create dynamic variable and how to add list of key,value pair values to it ?(Please read added comments)

Map sample = Map(); // creating sample named dynamic variable

List<TechData> data = [
{"title": 'Android', "date": '10/01/2019'},
{"title": 'Flutter', "date": '10/01/2019'},
{"title": 'Java', "date": '30/10/2019'},
];

sample['Android'] = [{}];  // initializing the dynamic variable

for (var i = 0; i < data.length; i++) {  // trying to add value using .add()
    if (data[i].title == 'Android') {
        sample['Android'].add(data[i]);
    }
}

when adding a value using .add() it causing an error as below.

Exception has occurred.

TypeError (type 'TechData' is not a subtype of type 'Map' of 'value')

Can anyone please provide any solution to solve this error?

Upvotes: 2

Views: 5860

Answers (1)

Harshvardhan Joshi
Harshvardhan Joshi

Reputation: 3193

Map sample; // declared but not initialized
sample['Android'] = 'Android'; // gives you error

If you want to use sample just replace the declaration with below code:

Map sample = Map();

or

Map<String, dynamic> sample = Map<String, dynamic>();

Both approaches are the same, The only change is that the second approach takes only String as key while first takes anything as a key(dynamic).

Update: The above map can be used as a storage for anything, since the value of the map remains dynamic. Any type of object can be passed as value to this map. Only concern is that when retrieving values make sure to cast it to the same object as the one passed as value.

e.g. :

map['numbers'] = [1,2,3,4]; // will work
map['strings'] = ['1','2','3','4']; // will work as well.

But when you retrieve the values, it will be as following: var listOfNumbers = map['numbers']; listOfNumbers will be a list make sure to cast it as int.

var listOfNumbers = map['numbers'].cast<int>(); 

Upvotes: 2

Related Questions