Extend String (Flutter)

From Dart 2.7, new method has been implemented called “Extension”. It is a way to add functionality to existing libraries.

Why to use extension?

Is’nt it better to use your own code rather than using someone else’s apis?
By the usage of extension feature we could implement our logic in our code. Also reduce the usage of external plugins (for eg. String Validators); if we are using someones plugins , it’s impractical to change the code according to our needs. (eg. If we want to modify string like : “Hello World” or “HeLlO wOrLd”).

How to use?

Syntax :

extension <extension name> on <type> {
(<member definition>)*
}

Here I will demonstrate how to use extension feature in String.

  1. Create a new dart file -> extension.dart
    Write the extension method in the dart file. Here I have written 5 sample codes for String modifications.
    # capsFirst -> Capitalize first letter of a word. “hello world” => “Hello world”.
    # allInCaps -> Capitalize all letters in a string. “Hello world”=> “HELLO WORLD”.
    # capitalizeFirstofEach -> Capitalize first letter of each word in a String.
    “hello world” => “Hello World”.
    # isEmail -> Check weather given string in an email.(returns true/false).
    #isUrl -> Check weather given string is URL. (returns true/false).
extension StringExtend on String {  String get capsFirst => this.length > 0  ?                                                                                                                                                                                    '${this[0].toUpperCase()}${this.substring(1)}' : '';  String get allInCaps => this.toUpperCase();  String get capitalizeFirstofEach => this.replaceAll(RegExp(' +'), ' ').split(" ").map((str) => str.capsFirst).join(" ");


bool get isEmail => RegExp(r"^(([^<>()\[\]\\.,;:\s@]+(\.[^<>()\[\]\\.,;:\s@]+)*)|(.+))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$").hasMatch(this);
bool get isUrl => RegExp(r'(http|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?').hasMatch(this);

}

2. Import the extension dart file like other libray files.

// Import a library that contains an extension method.
import 'extension.dart';
// ···
print("http://www.google.com".isUrl); // return True.
print("googlecom".isUrl); // return False.
print("anan@xxmail.co.in".isEmail); // returns True.
print("ananda".isEmail); // return False.
print("hello world, how are you?".capitalizeFirstofEach); //Hello World, How Are You?

Note:

  1. You cannot invoke extension feature in dynamic data types.
    dynamic val = '23';

var x = val.parseInt; // run time error

2. If two or more extensions have same name in different dart files, we have to import using some prefix.

Eg: import ‘extension.dart’;
import ‘extension_new.dart’ as extn;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store