Home > Net >  How to use generics in dart。
How to use generics in dart。

Time:01-06

I use generics in java usually with interface. I want to use generics like java. what should I do. I think use dynamic can not solve my issues.

CodePudding user response:

You could do something like this:

/// 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

  •  Tags:  
  • Related