Flutter & Dart Tips 01 — overwrite toString Method

Hussein Reda
2 min readSep 30, 2022

--

@Overwrite

This keyword is used for overwriting method in a super class

in dart any class you create extends Object {} class Even if it’s not explicitly written in the code.

one of these methods you can overwrite is toString() Method.

you need to overwrite method in super class if you want change Method behavior, Note that this doesn't violate LSP In SOLID Principles, Because

you use the same function signature (the same parameters with same types, and same return type).

for example, if you have a class Like that

if you print this class like that

you will get this “ Instance of ‘User’ “

and for some reason, you want to display class data to check its values for Your code debugging process, Instead of printing (user.id, user.name, …ect)

you can overwrite toString method in User class, like this

Now instead of returning a string of class type, you get your own statement for this class, and also you can use it in flutter as you want.

if you had a phone number class containing country code and phone number

you can make toString method return (“${phoneNumber.counterCode} ${phoneNumber.number}”). and so on for any complex situation.

it is a powerful method You should take advantage of it.

--

--

No responses yet