user1432751 user1432751 - 3 months ago 12
Dart Question

A value of type 'String' cannot be assigned to a variable of type 'Hero'

I am learning Dart. When I am writing next code:

class Hero
{
String name;

Hero(this.name);
}

class AppComponent
{
String title = 'header';
Hero hero = 'Windstorm';
}


Hero hero = new Hero('test');


I am getting error:
A value of type 'String' cannot be assigned to a variable of type 'Hero'
.

What I am doing wrong?

Answer

The problem seems to be in this line:

Hero hero = 'Windstorm';

hero is of type Hero. 'Windstorm' is of type String. So one cannot be assigned to the other just like that.

You can try this:

Hero hero = new Hero('Windstorm');

Just like you did in your last line with 'test'.

If there is a constructor for the class Hero that takes a string as an argument, then it will work.

Comments