0
I intend to create a dropdown
reusable with Flutter
, which is capable of receiving different lists of values as an argument. However, I get an error when creating a variable that will store the default value of the list.
This is my code:
class AndroidDropdown extends StatefulWidget {
AndroidDropdown({@required this.sourceList});
final List<String> sourceList;
@override
_AndroidDropdownState createState() => _AndroidDropdownState();
}
class _AndroidDropdownState extends State<AndroidDropdown> {
// O erro está aqui
String selectedItem = widget.sourceList[0];
@override
Widget build(BuildContext context) {
List<DropdownMenuItem<String>> dropdownItems = [];
for (String sourceListItem in widget.sourceList) {
DropdownMenuItem<String> newItem = DropdownMenuItem(
child: Text(sourceListItem),
value: sourceListItem,
);
dropdownItems.add(newItem);
}
return DropdownButton<String>(
value: selectedItem,
items: dropdownItems,
onChanged: (value) {
setState(() {
selectedItem = value;
});
},
);
}
}
The mistake is:
"The instance Member 'widget' can’t be accessed in an initializer. Try replacing the Reference to the instance Member with a Different Expression".