Dart - Read Keys and Values from a Map inside a Map - flutter

I have a variable with the following structure:
final Map<String, Map<double, String>> ingredients;
I need to access, as string, the "inner" map keys and values after indexing the external map:
ingredients.keys.elementAt(index)
The above code returns a "regular string", but when accessing the "inner" map:
ingredients.values.elementAt(index).keys
The result prints with round brackets around it. I suppose it occurs because the first example returns a string and the second returns an Itarable. But how do I make it a string without the round brackets?
.toString() does not work.
I can't make it a single Map<String, String> because I need the double value separated from the second string (a unit specification).
I will put the result inside a Flutter Text() widget inside a ListView.builder(), that is the reason of the indexing.
Resuming: I am getting (200)(g) and I need 200g.
Thanks for the attention. Any help is appreciated.

try this -
var _value = ingredients.values.elementAt(index).values;
print(_value.substring(1,_value.length-1));

Not a pretty solution but you can try: ingredients.values.elementAt(index).keys.toString().replaceAll(RegExp(r'[\(\)]'),'');
which will remove the parentheses anywhere in the keys.
I ran into the same problem as you did.
Hope this helps!

Related

Removing empty entry in List<dynamic> that only shows while inspecting

I have a list that I am getting the values from an API,
it is List<dynamic> type, while I print it I am getting this output (for example): [cat, female], but when I use inspect it has three values: "cat", "female", "". The last empty value is making some problems in my code, so I wanted to remove it, but I don't know how to do this.
As it is a List<dynamic> I used removeLast() and also toString() but none of them worked for me. I appreciate any help on this.
The solution is to filter items and get the new list:
final newList = list.where((e) => e != null && e != '').toList();
removeLast() does not work as you expected. If you read the comment of the method it says Removes and returns the last object in this list.
PS: I recommend you use a functional way to deal with a list which means do not modify the state of the original list instead, get a new list.

Dart: How to force string interpolation on a variable

I have a variable that contains a string with interpolated variables. In the code below, that variable is template. When I pass this variable to generateString function, I want to apply string interpolation on it because the values which interpolated variables require are available in generateString function only.
void main() {
String template = '<p>\${name}</p>';
var res = generateString(template);
}
generateString(template) {
var name = 'abc';
print(template);
return template;
}
The problem is when I am printing and returning template inside generateString fn, I am getting <p>${name}</p> instead of <p>abc</p>. Is there a way to explicitly tell the dart to so string interpolation?
I am new to Dart. I don't know if it is even possible to achieve or not. Please suggest how do I do this.
Edit: Based on the inputs from other users, I would like to make a clarification about the scenario presented. The value of template variable is not a string literal. I get that from UI as a user input. I have shown it here as a string literal for code simplicity. Also, please consider that name and template are not in the same scope in my scenario.
The other answers so far are wrong.
String interpolation (looking for $, etc) happens only while compiling from the source code to the value in memory. If that string in turn also has a $, it's no longer special.
It's not possible to trigger interpolation past the original compilation step. You can write a templating system that would look for something like {{name}} in the value, and replace it with the current value of name.
If you have the template and the variable in the same scope, it works as expected.
// evaluate variable inside ${}
var sport = 'basketball';
String template = 'I like <p>${sport}</p>';
print(template);
I didn't fully understand your question maybe this will help
void main() {
print(generateString('abc')); //<p>abc</p>
}
generateString(String template) {
return r"<p>" "$template" r"</p>";
}
Walter White here.
You must define the variable name as global var, so it can "cook" the string for you

Iterate over _InternalLinkedHashMap not working

I'm trying to iterate over the following data structure: {String: [{String, List<SomethingResponse>}]} where SomethingResponse = {String: dynamic}). I created this model:
class SomethingsResponse {
final Map<String, List<SomethingResponse>> SomethingsResponse;
SomethingsResponse({this.SomethingsResponse});
factory SomethingsResponse.fromJson(data) {
return SomethingsResponse(SomethingsResponse: data.map<String, List<SomethingResponse>>((String key, dynamic value) {
final dataFromCategory = List<SomethingResponse>.from(value.map((x) => SomethingResponse.fromJson(x)));
return MapEntry(key, dataFromCategory);
}));
}
}
When I try getting the keys like this: data.somethingsResponse.toList(), I get an error saying:
Class '_InternalLinkedHashMap<String, List>' has no instance method 'toList'.
I can't iterate over it or really get any kind of data out of it. What am I doing wrong and how can I fix it? I have a feeling the issue is at this line return MapEntry(key, dataFromCategory);, but I tried creating a Map a couple of different ways, and none worked.
If you consult the documentation for Map, you will see that it does not derive from Iterable and therefore cannot be directly iterated over. I presume that this is because it's not obvious what you want to iterate over: keys, values, or key-value pairs?
If you want to iterate over keys, use Map.keys. (In your case: data.somethingsResponse.keys.toList())
If you want to iterate over values, use Map.values.
If you want to iterate over key-value pairs (i.e. MapEntry objects), use Map.entries.

Is Map of lists not possible in dart?

I have data in this order :-
m={ 1:[54,23,98],
9:[8,4,2]
}
I'm trying to achieve something like this using the following code but it's not working. Where am I going wrong? Is there another way of storing and accessing this type of data in dart if my method is completely wrong?
Map<int,List<int>> m;
m[0]=[];
m[0].add(5);
You have to initialise it with empty map first
Map<int, List<int>> m={}; //<- initialise it here
m[0] = [];
m[0].add(5);
print(m); // prints {0: [5]}

unity,how to use generic by using js?

When I write like this
List.<Dictionary.<String, System.Object>>,
the ide tells me
Assets/Scripts/yhj/Model/PrintItem.js(23,71): BCE0044: expecting >, found '>>.
How can I resolve it?
Why would you make a list of dictionaries? Can't you just use the dictionary as the list with the key, value input instead of this? If you wanted to use it like this I would either define an object to be the <String, System.Object> and inserting that as the value and just leave the key as the number.
Or making a list of objects where the object is the <String, System.Object>
#ILiveForVR makes me think about this.thanks.
I solved it, but I'm not sure if the solution is best.
I do it like this:
var list = List.<System.Object>;
for(var i=0;i<list.Count;i++){
var data = list[i] as Dictionary<String, System.Object>;
}