Difference between "toString" and "as String" in Dart?

Viewed 714

Is there any difference between .toString and as String in Dart?

2 Answers

toString() is a method on Object and is therefore available on every object. The method is used to get a string representation of the object:

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string represetion.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

https://api.dart.dev/stable/2.13.4/dart-core/Object/toString.html

as String is a typecast in Dart and is used to tell the analyzer/compiler that whatever it assumes, you are now going to tell it that your object is in fact a String at runtime. You can hereafter use the object like a String.

But the compiler will add a check at runtime and if the object is not compatible with the interface of String, your application will crash because you have lied to the compiler.

It is therefore two entire different things and is used for different purposes. You can e.g. not use as String on an object which is not already a String.

The safest you can do is just call toString() since toString() on String will just return itself.

They are completely different!

.toString() is a method to represent data of a object but as String is a type cast which tries to convert the object itself to a String .

Imagine you have a class named Person

class Person {
  String firstName;
  String lastName;
  Person(
     this.firstName,
     this.lastName,
  );
}

now casting person to a String will lead to an _CastError error since Person is not a String or a subtype of String(inherited classes from String class)

final person = Person('sajad', 'abd');
final personAsString = person as String;

Meanwhile, the method .toString() will represent you object in a String.

final person = Person('sajad', 'abd');
final personToString = person.toString();
print(personToString); // result: Instance of 'Person'

.toString() is defined for every class in dart and you can override it in you custom classes

for example you can override it in Person class to represent firstname and lastname of person

class Person {
  String firstName;
  String lastName;
  Person(
     this.firstName,
     this.lastName,
  );

  @override
  String toString() => 'Person(firstName: $firstName, lastName: $lastName)';
}

And now the result of

final person = Person('sajad', 'abd');
final personToString = person.toString();
print(personToString);

would be

Person(firstName: sajad, lastName: abd)
Related