Dart Extension

Dart Extension

Hello guys!! In this article you will learn how to use extension in dart. After reading this article you will be able to use extension in dart.

What is extension ?

Using extension we can write or define our own methods or functions for a existing classes e.g: int, String etc.

Why we need extension ?

Suppose we want to parse a string into int. We can do this using

int.parse("45")        

But what if we want to do like this.

"45".parseToInt()        

Above code is easy to use. We can achieve this thing using a extension.

Syntax for defining extension

extension extension_name on class_name {
// Write your methods here.
}        

Now we will define extension on string.

extension ParseToInt on String {
  int parseToInt(){return int.parse(this);}
}        

Here our extension name is ParseToInt, we can give any name to it and method name is parseToInt, this method returns integer value. We can use this extension on any string, because it's defined for all strings. It gives FormateException when we pass a string which can not be converted into int.

Using this keyword we are getting the string value, that's why we don't need to define argument for parseToInt() .

Now we can use extension on any string. Using dot we can access all extensions which are defined for strings.

void main() {
  int value = "45".parseToInt();
  print(value);
}
// Output; 45        
You can learn more about extension on this

Thank you guys for reading article, If you have any doubt than you can ask me on linkedin.

Jayesh Pansheriya

Flutter | Dart | AngularDart | Firebase | RiverPod | GetX | RxDart | Android

1 年

要查看或添加评论,请登录

Bhushan Jadhav的更多文章

  • Generics in dart

    Generics in dart

    Hello! In this article, you’ll learn how to use the Dart generics. After reading this article you can easily use dart…

    2 条评论
  • Unit Test in Flutter

    Unit Test in Flutter

    Hello guys in this article we are going to learn how to write Unit test in Flutter . Unit test plays a very important…

  • How to use Native code in Flutter

    How to use Native code in Flutter

    Hello FlutterDevs, In this article we will learn, How we can use Native code in our Flutter Project for Android and i…

  • How to connect Firebase to our Flutter project

    How to connect Firebase to our Flutter project

    In this article i will teach you how we can connect Firebase to our Flutter project just follow all the steps given…

社区洞察

其他会员也浏览了