Solved: How to map array of objects in flutter?

Question

Asked by Ranko K on September 21, 2022 (source).

Hello I'm trying to map array of objects and return widget with some value of given objects... Like this

 _metapodaci?.map<Widget>((e) => Text("Naziv dokumenta je ${e.label}")),

I get an error saying "The element type 'Iterable' can't be assigned to the list type 'Widget" but when I map inside text widget like this:

 Text("Meta podaci: ${_metapodaci.map((e) => e.label)}"),

then _metapodaci are mapped good. Here is Whole widget where I'm trying to map if needed:

 Padding(
           padding: const EdgeInsets.all(8.0),
            
            child:   Expanded(
              child: _metapodaci.isEmpty ? 
              Text("Odaberite vrstu dokumenta") :
              Column(
                children: [
                  Text("Meta podaci: ${_metapodaci.map((e) => e.label)}"),
                  //_metapodaci.map<Widget>((e) => Text("Naziv dokumenta je ${e.label}")),
                ],
              ),
            ),
          ),

Appreciate if someone can advise. Thank you in advance!

Answer

Question answered by eamirho3ein (source).

You need to convert your array to list of widget and also for null safety issue you need check for null before too , try this:

Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Expanded(
                    child: _metapodaci == null || _metapodaci!.isEmpty
                        ? Text("Odaberite vrstu dokumenta")
                        : Column(
                            children: _metapodaci!
                                .map<Widget>((e) =>
                                    Text("Naziv dokumenta je ${e.label}"))
                                .toList(),
                          ),
                  ),
                ),
DART FLUTTER
SHARE: