我在Flutter中重构DropdownButton小部件的代码时遇到问题。我有简单的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中,仅将其“child”属性移至单独的小部件。但是然后我将不得不在主文件中管理DropdownMenuItem的“值”和其他属性。
最佳答案
DropdownButton
要求其项目为List<DropdownMenuItem>
。但是您的类FileListDropdownMenuItem
仅扩展了StatelessWidget。如果要使用它代替DropdownMenuItem
,则应扩展它:
class FileListDropdownMenuItem extends DropdownMenuItem {
FileListDropdownMenuItem(
String labelText,
bool showSelectedMark,
String itemValue,
) : super(
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(labelText),
if (showSelectedMark)
Icon(Icons.check)
],
),
),
value: itemValue,
);
}
关于flutter - 单独的窗口小部件文件中的Flutter DropdownMenuItem,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62070215/