Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of widgets from map with keys and values

Tags:

flutter

dart

If I have say a SimpleDialog() and it accepts children[] and I want to populate it from a Map<int, String>, how would I do that? I need both the key and value to create the child widget.

const optionsMap = {
    111:"First option",
    222:"Second option",
}
return SimpleDialog(
    title: Text('Choose one'),
    children: // I don't know what to put here
              // I want to have widgets based on optionsMap keys and values
)

I solved it by creating a List<Widget> beforehand above the return statement, but just for convenience (and becoming better in Dart) I'd like to know if there's a way to do it inline.

like image 227
TimSim Avatar asked Mar 07 '19 09:03

TimSim


People also ask

What is key in widgets flutter?

Well, Keys are the ones to preserve state when widgets move around the widget tree. It is used to preserve the user scroll location or keeping state when modifying a collection.


1 Answers

Update answer to incorporate @lrn 's comment

You can use map

const optionsMap = {
    111:"First option",
    222:"Second option",
}     
    return SimpleDialog(
        title: Text('Choose one'),
        children: optionsMap.entries.map((entry) {
          var w = Text(entry.value);
          doSomething(entry.key);
          return w;
        }).toList());
;
like image 112
TruongSinh Avatar answered Sep 30 '22 08:09

TruongSinh