【问题标题】:Return same object type user provided in Dart返回 Dart 中提供的相同对象类型用户
【发布时间】:2021-07-24 05:36:22
【问题描述】:

所以我有这个我正在为颤振编写的小部件,它是一个类似于刷卡的 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);
  }
)

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

【问题讨论】:

  • 问题是什么?如果您希望 Swipeable 是通用的,您需要这样做:class Swipeable&lt;T&gt; extends StatelessWidget
  • 我希望构建器函数的第二个参数与提供的列表类型相同

标签: flutter dart widget


【解决方案1】:

您可以为此使用泛型类。 如需更多信息,请参阅语言导览中的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&lt;Type&gt; 指定类型。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多