我在 Flutter 中重构 DropdownButton 小部件的代码时遇到问题。我有简单的下拉按钮。
DropdownButton(
items: [
DropdownMenuItem(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Ascending'),
if (widget.currentDateSortOrder == SortOrderType.Ascending)
Icon(Icons.check)
],
),
),
value: 'Asc',
),
DropdownMenuItem(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Descending'),
if (widget.currentDateSortOrder == SortOrderType.Descending)
Icon(Icons.check)
],
),
),
value: 'Desc',
)
],
onChanged: (itemIdentifier) {
...
},
)
我想将 DropdownMenuItem 移动到单独的小部件以使我的小部件树更精简。所以我然后移动了它。
import 'package:flutter/material.dart';
class FileListDropdownMenuItem extends StatelessWidget {
final String labelText;
final bool showSelectedMark;
final String itemValue;
FileListDropdownMenuItem(this.labelText, this.showSelectedMark, this.itemValue);
@override
Widget build(BuildContext context) {
return DropdownMenuItem(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(labelText),
if (showSelectedMark)
Icon(Icons.check)
],
),
),
value: itemValue,
);
}
}
当我尝试像这样在 DropdownButton 中使用它时:
...
items: [
FileListDropdownMenuItem(
'Ascending',
widget.currentDateSortOrder == SortOrderType.Ascending,
'Asc')
],
...
我收到此错误:
The argument type 'List<FileListDropdownMenuItem>' can't be assigned to the parameter type 'List<DropdownMenuItem<dynamic>>'.
有没有办法使这种方法起作用?我知道我可以将 DropdownMenuItem 留在 DropdownButton 中,并将其仅“子”属性移动到单独的小部件。但是,我将不得不在主文件中管理 DropdownMenuItem 的“值”和其他属性。