首页 > 解决方案 > 返回 Dart 中提供的相同对象类型用户

问题描述

所以我有这个我正在为颤振写的小部件,它是一个类似于刷卡的 Tinder,我希望消费者能够提供他想要的任何类型的列表,并且我想使用他提供的相同类型返回他应该提供的builder方法:

class Swipeable extends StatelessWidget {
  final List<T> data;
  final Widget Function(BuildContext, T) builder;

  Swipeable({required this.data, required this.builder});
}

其中T是用户提供的数据类型,由用户控制,不受我的限制。

消费者应该能够像这样使用小部件:

Swipeable(
  data: <User>[
    User(
      name: "Zakaria",
      profession: "Geek",
      images: [
        "https://images.unsplash.com/photo-1533488069324-f9265c15d37f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=594&q=80",
        "https://images.unsplash.com/photo-1583864697784-a0efc8379f70?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80",
      ],
      age: 18,
    )
  ],
  builder: (context, user) {
    return Text(user.name);
  }
)

我希望你理解我的问题,当我还是个新手时,我不太擅长解释东西。

标签: flutterdartwidget

解决方案


您可以为此使用通用类。有关更多信息,请参阅语言导览中的泛型部分。

// The class  ( ↓ note the type argument here)
class Swipeable<T> extends StatelessWidget {
  final List<T> data;
  final Widget Function(BuildContext, T) builder;

  Swipeable({required this.data, required this.builder});
}

类型推断应该在您的示例中有效(您甚至不需要指定列表类型),但如果没有,您可以使用Swipeable<Type>.

另一方面,您甚至可能不需要像这样遍历您的列表。考虑ListViewand GridViewbuilder 构造函数,它们提供索引而不是对象。为了保持一致性,您可能想要做同样的事情。


推荐阅读