如何在dart中使用泛型。

How to use generics in dart。

我在 java 中使用泛型,通常使用接口。我想使用像 java 这样的泛型。我应该怎么办。我认为使用动态不能解决我的问题。

你可以这样做:

/// To make an interface in Dart you can create an abstract class.
///
/// Then you can define a generic type with <T>.
///
/// In this sample I'm using <T extends Object> to ensure
/// that I'm not passing a nullable type (such as String?).
abstract class MyInterface<T extends Object> {
  T get myValue;
}

/// Then you can implement your interface like this.
class MyInterfaceImplementation implements MyInterface<String> {
  @override
  final String myValue;
  
  MyInterfaceImplementation(this.myValue);
}

Try the full code on DartPad