我想在 BottomNavigationBar 项目中使用 DropdownButton。但无法使用 setState()。我看到了这个错误:- 无法在初始化程序中访问实例成员“setState”。尝试用不同的表达式替换对实例成员的引用dart(implicit_this_reference_in_initializer)
还有这个错误:- 无法在初始化程序中访问实例成员“numDropdownVal”。尝试用不同的表达式替换对实例成员的引用dart(implicit_this_reference_in_initializer)
这是完整的代码:
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
String numDropdownVal = 'One';
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions() {
return<Widget>[
Container(
child: DropdownButton<String>(
isExpanded: true,
value: numDropdownVal,
items: <String>[
'One',
'Two',
'Three',
'Four',
'Five',
'Six'
].map((name) {
return DropdownMenuItem<String>(
value: name,
// Your row here:
child: Text(
name,
style: TextStyle(fontSize: 18),
),
);
}).toList(),
onChanged: (selectedName) {
setState(() {
numDropdownVal = selectedName;
});
},
),
),
Text(
'Other page',
style: optionStyle,
),
Text(
'Another page',
style: optionStyle,
),
];
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}