Search code examples
darttypesassert

How to implement `assert()` for Type / T


to reproduce:

  • create an empty project
  • paste the code below in main.dart
  • press f5 (in vs code, else just run the app)

note that dartpad ignores assert

class Foo<T> {
  Foo(this.data) : assert(T is int || T is String);
  final T data;
}

void main() {
  print('hello');
  final _fooInt = Foo<int>(1);
}

logs:

flutter: hello
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:type_test/main.dart': Failed assertion: line 2 pos 27: 'T is int || T is String': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      new Foo
package:type_test/main.dart:2
#3      main
package:type_test/main.dart:8
#4      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:136:25)
#5      _rootRun (dart:async/zone.dart:1186:13)
#6      _CustomZone.run (dart:async/zone.dart:1090:19)

How can I implement correctly the assertion on line 2? Thank you


Solution

  • credit to Stampi from the answer on r/flutterDev discord

    the change below fixes the issue

    class Foo<T extends int> {
    - Foo(this.data) : assert(T is int || T is String);
    + Foo(this.data) : assert(T == int || T == String);
      final T data;
    }
    
    void main() {
      print('hello');
      final _fooInt = Foo<int>(1);
      print(_fooInt.data.runtimeType);
    }