flutter - 返回 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);
}
)
我希望你理解我的问题,当我还是个新手时,我不太擅长解释东西。
解决方案
您可以为此使用通用类。有关更多信息,请参阅语言导览中的泛型部分。
// 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>
.
另一方面,您甚至可能不需要像这样遍历您的列表。考虑ListView
and GridView
builder 构造函数,它们提供索引而不是对象。为了保持一致性,您可能想要做同样的事情。
推荐阅读
- python - 用另一个字典初始化一个 Python 字典
- javascript - 如何在 2 种形式的情况下知道我正在使用正确的数据?
- python - QGraphicsObject 需要显式更新才能重绘
- java - 'where子句'java中的未知列
- excel - 在工作表更改中每 10 秒清除一次单元格
- python - 使用 range 命令迭代 url 以进行网页抓取
- c# - 解析在启动时注册的 Main.cs 中的服务
- angular - 当我在 httpClient 中发现错误时如何获取 json 正文
- php - 如何使用 php 在 twitter 卡中查看用户的用户名?
- kubernetes - Kubernetes Pods - 从主机节点注入环境变量