1

我在 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 的“值”和其他属性。

4

1 回答 1

1

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,
  );
}
于 2020-05-28T17:27:12.793 回答