Kozimir
Kozimir

Reputation: 83

runtimeType check of generic List object in Dart

I am trying to do flow control based on type in Flutter and I came across this. Is this normal?

List<Widget> getDetailDisplayWidget() {
  var retval = List<Widget>();

  List<String> test = <String>["something"];
  print(test.runtimeType is List);
  print(test.runtimeType is List<String>);
  print(test.runtimeType == List);

  this._databaseModel.forEach((key, value) {
    switch (value.runtimeType) {
      case String:
        retval.add(SingleValueDetail(
            question: _questionModel[key]["question"],
            label: _questionModel[key]["label"],
            variable: _questionModel[key]["variable"],
            key: key));
        break;
      case Timestamp:
        retval.add(DateValueDetail(
            question: _questionModel[key]["question"],
            variable: _questionModel[key]["variable"],
            key: key));
        break;
      case List:
        retval.add(ListValueDetail(
            question: _questionModel[key]["question"],
            label: _questionModel[key]["label"],
            variable: _questionModel[key]["variable"],
            key: key));
        break;
      default:
        retval.add(ListValueDetail(
            question: _questionModel[key]["question"],
            label: _questionModel[key]["label"],
            variable: _questionModel[key]["variable"],
            key: key));
        //retval.add(Text("Unknown widget type"));
        break;
    }
  });
  return retval;
}

Output:

Performing hot restart...
Syncing files to device iPhone SE...
Restarted application in 1,710ms.
flutter: false
flutter: false
flutter: false

Dart version:

Dart VM version: 2.7.2 (Mon Mar 23 22:11:27 2020 +0100) on "macos_x64"

Upvotes: 2

Views: 4220

Answers (1)

Zakir
Zakir

Reputation: 1565

You can check the type of a List by simply using if statement like

if (test is List<String>) {
}

If you print print(test.runtimeType) it will give you List<String>. One way you can use the runtimeType like this.

 switch(test.runtimeType.toString()) {
      case "List<String>":
        print(true);
        break;
      default:
        print(false);
    }

I prefer the first option. You don't know toString method implementation can be changed any time.

Upvotes: 3

Related Questions