假设我有一些以泛型类型为参数的函数.如何在该函数中判断泛型类型参数是否可以为空?我想做这样的事情:

void func<T>() {
  print(T is nullable);
}

void main(){
  func<int>(); //prints false
  func<int?>(); //prints true
}

我能想到的唯一办法就是判断T.toString()是否以?结尾,这很让人毛骨悚然.

推荐答案

try :

bool isNullable<T>() => null is T;

Dart相关问答推荐

如何防止 Riverpod 的 ConsumerWidget 重建管理 ThemeMode

为什么 Dart 的编译器认为代码可能为空,而代码保证它不能为空?

dart - 通过异步等待避免递归 Stackoverflow

如何为屏幕设置不同的主题?

设置文本以匹配Flutter中的列宽

在 Dart 中,List.unmodifiable() 和 UnmodifiableListView 有什么不同?

如何使我的Flitter应用程序的导航抽屉(Navigation Drawer)透明?

判断 Future 是否完整

不要将 PageView 居中 - Flutter

Dart:Streams与 ValueNotifiers

为什么这个文件会自动创建自己 generate_plugin_registrant.dart

'dart:async' 的函数 `runZoned` 的用途

Dart:你如何让 Future 等待 Stream?

如何在 Dart 中以正确的方式重定向和重新加载?

如何在 Dart 中读取控制台输入/标准输入?

在 Dart 中没有换行符的 print()?

Dart 中的 urlencoding

Dart 中的函数重载

dart 折叠(Fold)与减少(Reduce)

Dart 中的函数类型定义(typedefs)/函数类型别名(function-type aliases)是什么?