我从不久前开始使用Flutter,所以我没有足够的经验来处理小部件,我想创建一个包含许多列表的页面,我在YouTube上找到了一段视频,解释如何制作一个列表,但是为每个新列表重复代码是没有意义的,您是否有一种方法可以使用相同的代码,但在同一页面中使用不同的列表?
代码:
class FileLangs extends StatefulWidget {
@override
_FileLangsState createState() => _FileLangsState();
}
class Langs {
int id;
String name;
Langs(this.id, this.name);
static List<Langs> getLangs() {
return <Langs>[
Langs(1, 'Arabic'),
Langs(2, 'English'),
Langs(3, 'English & Arabic'),
];
}
}
class _FileLangsState extends State<FileLangs> {
List<Langs> _langs = Langs.getLangs();
List<DropdownMenuItem<Langs>> _dropdownMenuItems;
Langs _selectedLangs;
@override
void initState() {
super.initState();
_dropdownMenuItems = buildDropdownMenuItems(_langs);
_selectedLangs = _dropdownMenuItems[0].value;
}
List<DropdownMenuItem<Langs>> buildDropdownMenuItems(List langs) {
List<DropdownMenuItem<Langs>> items = List();
for (Langs lang in langs) {
items.add(
DropdownMenuItem(
value: lang,
child: Text(lang.name),
),
);
}
return items;
}
onChangeDropdownItem(Langs selectedLangs) {
setState(() {
_selectedLangs = selectedLangs;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"Select Language",
style: TextStyle(color: Colors.white, fontSize: 14),
),
Container(
child: DropdownButton(
isExpanded: true,
value: _selectedLangs,
items: _dropdownMenuItems,
onChanged: onChangeDropdownItem,
),
),
],
),
),
);
}
}
答案 0 :(得分:0)
添加此模型类
class Langs {
const Langs(this.id, this.name);
final int id;
final String name;
}
如下更改您的buildDropdownMenuItems方法
List<DropdownMenuItem<Langs>> buildDropdownMenuItems(List langs) {
List<DropdownMenuItem<Langs>> items = const <DropdownMenuItem<Langs>>[
const Langs(1, 'Arabic'),
const Langs(2, 'English'),
const Langs(3, 'English & Arabic'),
];
for (Langs lang in langs) {
items.add(
DropdownMenuItem(
value: lang,
child: Text(lang.name),
),
);
}
return items;
}
如下更改您的onChangeDropdownItem方法
void onChangeDropdownItem(Langs selectedLangs) {
if (selectedLangs == 'Arabic') {
setState(() {
_selectedLangs = selectedLangs;
});
} else if (selectedLangs == 'English') {
setState(() {
_selectedLangs = selectedLangs;
});
}else if (selectedLangs == 'English & Arabic') {
setState(() {
_selectedLangs = selectedLangs;
});
}else{
return null;
}
}