微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

返回 Dart 中提供的相同对象类型用户

如何解决返回 Dart 中提供的相同对象类型用户

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

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

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

解决方法

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

// 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> 指定类型。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。