Home > Blockchain >  Flutter 2.5.0, casting parent to child class fails (ok in 1.22.6)
Flutter 2.5.0, casting parent to child class fails (ok in 1.22.6)

Time:09-21

I am migrating from Flutter 1.22.6 to 2.5.0 (dart 2.14) and have a question on explicit casting.

In my code I have a plugin API that returns a base class object:

Future<BaseData> getReport(String type) async {
  return BaseData.fromJson(json.decode(report))
}

The BaseData.fromJson can build a number of different child object, like this:

static BaseData fromJson(Map<String, dynamic> json) {
  switch (json['type'] as String) {
    case 'typeOne':
      return ChildDataOne.fromJson(json);
    case 'typeTwo':
      return ChildDataTwo.fromJson(json);
   etc

Then I call the plugin function like this:

ChildDataOne childDataTypeOne = await dataManager.getReport(String type)

and in Flutter 1.22.6 this works fine. A ChildDataOne object is returned because the BaseData.fromJson constructor always builds the correct child type and no explicit casting is needed.

However, in Flutter 2.5.0 I get:

A value of type 'BaseData' can't be assigned to a variable of type 'ChildDataOne'.

I can of course cast it such as:

final childDataTypeOne = await dataManager.getReport() as ChildDataOne;

but I am unclear on why this is needed in Flutter 2.5.0 when it was not required in 1.22.6 or if I am doing something the wrong way.

All comments are welcome.

CodePudding user response:

It's not the Flutter or Dart version which makes the difference but the minimum Dart version in the pubspec.yaml file.

With the minimum Dart version at 2.11.0 your code works, also with Dart 2.14.0.

environment:
  sdk: ">=2.11.0 <3.0.0"

Once you change to the minium version 2.12.0 your code fails to compile.

environment:
  sdk: ">=2.12.0 <3.0.0"

If you use the minimum version 2.12.0, "non-nullable by default" gets automatically activated.

The error which you get is using the templateInvalidAssignmentError. This error is raised by the method ensureAssignable in type_inferrer.dart. Within that method there are multiple uses of the isNonNullableByDefault property. One of them invalidates your code.

  • Related