Using extensions
Extensions allow you to add methods and properties to existing classes, without modifying the original class.
With extensions, you extend the functionality of classes, and this is especially useful when you extend classes that you cannot modify.
Getting ready
To follow along with this recipe, you can write the code in DartPad.
How to do it...
To create a new method that extends the String
class, follow these steps:
- Create an
extension
calledStringExtensions
for theString
class that adds a method calledtoBool
, which returnsfalse
when the string is empty, andtrue
when it’s not:extension StringExtensions on String { bool toBool() { return isNotEmpty; } }
- Create a method that calls the
toBool()
method on two strings, one empty and another with some content:void testExtension() { String emptyString = ""; String nonEmptyString = "Hello Extensions!"; print(emptyString...