Ezaz Gouri
Ezaz Gouri

Reputation: 131

How to convert List<dynamic> to List<Object> in Flutter

I have made two Lists List <Animal> _animals and List <Animal> _selectedanimals

static List<Animal> _animals = [
    Animal( name: "Tiger"),
    Animal(name: "Lion"),
    Animal( name: "Panda"),
    Animal( name: "Anaconda"),];

  List<Animal> _selectedAnimals2 = [];

Then I made a multiselect sheet where the user can select his favorite animals and on confirm/or selected by the user the selected values are stored in a dynamic List named as values and from List<dynamic> values it is stored into another list List<Animal> _selectedAnimals2 but i m getting an error which is mentioned below :

type 'List<dynamic>' is not a subtype of type 'List<Animal>'

MultiSelectBottomSheetField(
                         initialChildSize: 0.4,
                         listType: MultiSelectListType.CHIP,
                         searchable: true,
                         buttonText: Text("Favorite Animals",style: GoogleFonts.montserrat(color: Colors.white),),
                         title: Text("Animals"),
                         items: _items,
                         onConfirm: (values) {
                            _selectedAnimals2=values;
                            final List<String> choose=_selectedAnimals2.map((Animal animal) => animal.name).toList();
                           saveUserInfoToFireStore(choose);
                         },

Upvotes: 11

Views: 20608

Answers (3)

Ferer Atlus
Ferer Atlus

Reputation: 288

List<CustomModel> toResponseList(List<dynamic> data) {
    List<CustomModel> value = <CustomModel>[];
    data.forEach((element) {
      value.add(NasaResponseModel.fromJson(element));
    });
    return value ?? List<CustomModel>.empty();
  }

works for me :)

Upvotes: 2

Afinas EM
Afinas EM

Reputation: 3215

if we want to convert list dynamic to its type, we can use the method cast()

List sample = ["test1", "test2"]; /// dynamic list

List<String> stringList = []; /// string list

/// for casting
stringList = sample.cast<String>();

Similarly, we can convert our lists

List<CustomModel> list = dynamicList.cast<CustomModel>();

Upvotes: 26

Moaid ALRazhy
Moaid ALRazhy

Reputation: 1744

if your _items is List of Strings you can try this

_selectedAnimals2 = values.map((val) => Animal( name: val)).toList()

Upvotes: 0

Related Questions