Home > OS >  A value of type 'List<Object?>' can't be assigned to a variable of type 'L
A value of type 'List<Object?>' can't be assigned to a variable of type 'L

Time:11-15

I have a custom Muscle Class:

class Muscle {
  final int id;
  final String name;

  Muscle({
    required this.id,
    required this.name,
  });
}

I'm using a package named multi_select_flutter and I'm running into a problem assigning here from values to _selectedMuscles:

MultiSelectChipField(
                        items: _items,
                        initialValue: _muscles,
                        title: Text("Select Muscles"),
                        headerColor: Colors.blue.withOpacity(0.5),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.blue, width: 1.8),
                        ),
                        selectedChipColor: Colors.blue.withOpacity(0.5),
                        selectedTextStyle: TextStyle(color: Colors.blue[800]),
                        onTap: (values) {
                          _selectedMuscles = values;
                        },
                      ),

The full error I get is:

A value of type 'List<Object?>' can't be assigned to a variable of type 'List<Muscle>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Muscle>'

I have tried casting using: _selectedMuscles = (List<Muscle>)values; but that doesn't work. Any ideas on how I can cast?

CodePudding user response:

Where did you define _items and _muscles? What types are they? Did you maybe forget to properly type them and one of them is just a List instead of a proper type like List<Muscle>?

Anyway, you can always override the automatic inference of the type argument and do it yourself:

MultiSelectChipField<Muscle>(

Then you will probably get compiler errors telling you where you missed the correct type.

CodePudding user response:

you can do like this

List<Object?> _items = ....;
List<Muscle> muscleList = _items.map((e)=>Muscle(e)).toList();
  • Related