我想将选定的值从 DropDown 传递给它的父级,然后通过构造函数传递给子级,然后通过 setState 函数更新列表。
所以,我希望从下拉列表中选择的值可以在限制(UserOffers)的子项中访问。
将数据从父级发送到子级它实际工作,但只有当我通过构造函数将父类中定义的数据传递给子级时=我不确定它是否是一个好方法。
现在我只使用提供程序来更新 Dropdown 上的数据,但我不知道如何传递它。
CountryProvider 类:
class CountryProvider with ChangeNotifier {
List<String> _items = [
"Argentina",
"Brazil",
...
"Spain",
"Switzerland",
];
String _selectedItem;
List<String> get items => _items;
String get selected => _selectedItem;
void setSelectedItem(String s) {
_selectedItem = s;
notifyListeners();
}
}
CountryDropDown 类:
class CountryDropDown extends StatefulWidget {
@override
_CountryDropDownState createState() => _CountryDropDownState();
}
class _CountryDropDownState extends State<CountryDropDown> {
@override
void initState() {
super.initState();
}
...
ChangeNotifierProvider<CountryProvider>(
create: (context) => CountryProvider(),
child: Container(
width: 215,
child: Consumer<CountryProvider>(
builder: (_, provider, __) {
return DropdownButton<String>(
hint: Text("Not selected"),
icon: Icon(Icons.flight),
value: dropdownValue,
onChanged: (String newValue) {
provider.setSelectedItem(newValue);
dropdownValue = provider.selected;
print(newValue);
},
items: provider.items
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
...
和家长:
限制类:
class Restrictions extends StatefulWidget {
@override
_RestrictionsState createState() => _RestrictionsState();
}
class _RestrictionsState extends State<Restrictions> {
@override
void initState() {
super.initState();
}
...
Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20),
child: FieldDropDown(),
),
Container(
padding: EdgeInsets.only(top: 10),
margin: EdgeInsets.only(left: 20),
child: CountryDropDown(),
),
],
),
Container(
child: DateSelector(),
),
],
),
Container(
child: UserOffers(
country: selectedCountry,
field: selectedField,
),
...