Ranko Koturic
Ranko Koturic

Reputation: 127

How to map array of objects in flutter?

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!

Upvotes: 0

Views: 2025

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17950

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(),
                          ),
                  ),
                ),

Upvotes: 1

Sugan Pandurengan
Sugan Pandurengan

Reputation: 723

Use toList() method

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

Upvotes: 1

Related Questions