颤振下拉菜单菜单项在单独的小部件文件中



我在 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) {
...
},
)

我想将下拉菜单项移动到单独的小部件,以使我的小部件树更精简。所以我然后移动了它。

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,
);
}
}

当我尝试像这样在下拉按钮中使用它时:

...
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的"值"和其他属性。

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,
);
}

最新更新