颤振:无法分配给参数类型“ T”

时间:2020-06-09 15:38:26

标签: flutter generics dart

我正在尝试创建泛型PopupMenuButton以使用我想使用的每个位置,因此我创建了这个泛型类:

class PopupMenuHelper<T> {
Widget showPopupMenu() {
    return Theme(
      data: Theme.of(context).copyWith(cardColor: Colors.greenAccent),
      child: PopupMenuButton<T>(
        shape: RoundedRectangleBorder(
            side: BorderSide(color: Colors.black),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15.0),
              bottomLeft: Radius.circular(15.0),
            )),
        onSelected: (value) {
          print("value:$value");
          callBack(T);
        },
        itemBuilder: (context) => [
          PopupMenuItem<T>(value: T, child: Text("Profile")),
          PopupMenuItem<T>(value: T, child: Text("Profile2")),
        ],
        icon: Icon(Icons.more_horiz),
        offset: Offset(0, 100),
        elevation: 8,

PopupMenuItem中,我将项目声明为T型,但在值上却出现错误:

The argument type 'Type' can't be assigned to the parameter type 'T'.dartargument_type_not_assignable

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您不应将T作为值传递给PopupMenuItem构造函数,而应指的是T类型的实际对象。您可以将其作为showPopupMenu的参数传递,也可以在PopupMenuHelper的构造函数中传递。