How to create a reusable dropdownButton in Flutter

Asked

Viewed 287 times

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".

1 answer

0


Try making this statement within the method initState:

String selectedItem;
@override
void initState() {
    super.initState();
    selectedItem = widget.sourceList[0];
}

(This method should be overwritten in its status class, _AndroidDropdownState.)

The line was error because it was executed at the time of class creation _AndroidDropdownState. At this time, you cannot access the property widget for it depends on an instance of that class, giving the error. The method initState is called when the object is inserted into the widgets tree, and therefore Property widget will already exist.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.