<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Phuc Tran</title>
    <description>The latest articles on DEV Community by Phuc Tran (@thphuc).</description>
    <link>https://dev.to/thphuc</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F168119%2F9ef4f26a-a433-4798-9cd1-bb9876f8b800.jpeg</url>
      <title>DEV Community: Phuc Tran</title>
      <link>https://dev.to/thphuc</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thphuc"/>
    <language>en</language>
    <item>
      <title>Dart/Flutter — How to parse String to number</title>
      <dc:creator>Phuc Tran</dc:creator>
      <pubDate>Sat, 07 Nov 2020 13:19:57 +0000</pubDate>
      <link>https://dev.to/thphuc/dart-flutter-how-to-parse-string-to-number-j79</link>
      <guid>https://dev.to/thphuc/dart-flutter-how-to-parse-string-to-number-j79</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk8d6s7c8h97kotx5zfcg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk8d6s7c8h97kotx5zfcg.png" alt="Dart extension methods" width="502" height="459"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post, let’s learn a few methods to parse/convert String to number (integer, double or both).&lt;/p&gt;

&lt;h1&gt;
  
  
  1. Use parse() method (not recommended)
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/// Parse string to integer
int stringToInt_parse(String input) {
  return int.parse(input, onError: (error) {
    // Return null if input string is invalid.
    // Change to default value if you want.
    return null;
});

/// Parse string to double
double stringToDouble_parse(String input) {
  return double.parse(input, (error) {
    // Return null if input string is invalid.
    // Change to default value if you want.
    return null;
  });
}

/// Parse string to number
num stringToNumber_parse(String input) {
  return num.parse(input, (error) {
    // Return null if input string is invalid.
    // Change to default value if you want.
    return null;
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Test it
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  final testInt = '100';
  final testDouble = '100.1';
  final testInvalidNumber = 'a';

  print(stringToInt_parse(testInt)); // 100
  print(stringToDouble_parse(testInt)); // 100.0
  print(stringToNumber_parse(testInt)); // 100

  print(stringToInt_parse(testDouble)); // null
  print(stringToDouble_parse(testDouble)); // 100.1
  print(stringToNumber_parse(testDouble)); // 100.1

  print(stringToInt_parse(testInvalidNumber)); // null
  print(stringToDouble_parse(testInvalidNumber)); // null
  print(stringToNumber_parse(testInvalidNumber)); // null
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Notes:
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We can use double.parse() to convert a valid integer string to int, but it will return a double (Line 7: 100.0). And obviously we can not convert a valid double string to integer, it will return null (Line 10: null).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;With num.parse(), the program will try to parse to integer first, if it can not parse (get null), then it will try to parse to double. (That’s why at line 8, the output is 100 but not 100.0).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I don’t know exactly the reason behind this, but if you look at the signature of the int.parse(), double.parse() and num.parse(), you will see that onError is optional named parameter in int.parse() while with double.parse() and num.parse() it is optional positional parameter. 🤔 🤔 🤔&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Look at onError:
int.parse(input, onError: (error) {
  // ...
});

// No need onError: 
double.parse(input, (error) {
  // ...
});

// No need onError: 
num.parse(input, (error) {
  // ...
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;If you don’t provide onError method to handle the exception with invalid string, the program will throw an exception at runtime.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/// Parse string to integer without handling error 
/// -&amp;gt; throw exception at runtime.
int stringToInt_parseWithoutErrorHandle(String input) {
  return int.parse(input);
}

void main() {
  final testInvalidNumber = 'a';
  print(stringToInt_parseWithoutErrorHandle(
   testInvalidNumber)
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Exception:
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
a
^

#0      int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
#1      int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
#2      int._parse (dart:core-patch/integers_patch.dart:100:12)
#3      int.parse (dart:core-patch/integers_patch.dart:63:12)
#4      stringToInt_parseWithoutErrorHandle (package:dart/core/string/string_to_number.dart:58:14)
#5      main (package:dart/core/string/string_to_number.dart:18:9)
#6      _startIsolate.&amp;lt;anonymous closure&amp;gt; (dart:isolate-patch/isolate_patch.dart:301:19)
#7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;(Important) At the beginning, I highlighted that this parse() method is not recommended. The dart document says (source):
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* ...
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) =&amp;gt; ...)`,
* you should use `int.tryParse(string) ?? (...)`.
* ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As mentioned above, we should use tryParse() method instead. Let’s move to that method immediately.&lt;/p&gt;

&lt;h1&gt;
  
  
  2. Use tryParse() method
&lt;/h1&gt;

&lt;p&gt;When using tryParse() method, we just need to provide the input String. In case the input is invalid, the program will return null. This is the difference between tryParse() and parse() (which throws exception if we don’t handle onError method).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int stringToInt_tryParse(String input) {
  return int.tryParse(input);
}

double stringToDouble_tryParse(String input) {
  return double.tryParse(input);
}

num stringToNumber_tryParse(String input) {
  return num.tryParse(input);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Test it
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  final testInt = '100';
  final testDouble = '100.1';
  final testInvalidNumber = 'a';

  print(stringToInt_tryParse(testInt)); // 100
  print(stringToDouble_tryParse(testInt)); // 100.0
  print(stringToNumber_tryParse(testInt)); // 100

  print(stringToDouble_tryParse(testInt)); // 100.0
  print(stringToDouble_tryParse(testDouble)); // 100.1
  print(stringToNumber_tryParse(testDouble)); // 100.1

  print(stringToInt_tryParse(testInvalidNumber)); // null
  print(stringToDouble_tryParse(testInvalidNumber)); // null
  print(stringToNumber_tryParse(testInvalidNumber)); // null
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  3. (Bonus) Use extension methods
&lt;/h1&gt;

&lt;p&gt;In case you don’t know what extension methods is, it is a way to add more functions to existing libraries/classes. In our case, we use this technique to add 3 methods to String class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension StringExtension on String {
  int toInt() {
    return int.tryParse(this);
  }

  double toDouble() {
    return double.tryParse(this);
  }

  num toNumber() {
    return num.tryParse(this);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After creating above extension, now our String has 3 more methods that we can use as other exiting methods. So cool! 😎 😎 😎&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  final testInt = '100';
  final testDouble = '100.1';
  final testInvalidNumber = 'a';

  print(testInt.toInt()); // 100
  print(testInt.toDouble()); // 100.0
  print(testInt.toNumber()); // 100

  print(testDouble.toInt()); // null
  print(testDouble.toDouble()); // 100.1
  print(testDouble.toNumber()); // 100.1

  print(testInvalidNumber.toInt()); // null
  print(testInvalidNumber.toDouble()); // null
  print(testInvalidNumber.toNumber()); // null
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s it!&lt;br&gt;
You can find original article on &lt;a href="https://coflutter.com/dart-flutter-how-to-parse-string-to-number/" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dart</category>
      <category>flutter</category>
      <category>stringtonumber</category>
      <category>nextfunc</category>
    </item>
    <item>
      <title>String in Dart/Flutter – Things you should know</title>
      <dc:creator>Phuc Tran</dc:creator>
      <pubDate>Mon, 17 Aug 2020 17:37:50 +0000</pubDate>
      <link>https://dev.to/thphuc/string-in-dart-flutter-things-you-should-know-2baf</link>
      <guid>https://dev.to/thphuc/string-in-dart-flutter-things-you-should-know-2baf</guid>
      <description>&lt;p&gt;String is an important data type in almost programming languages (if not all). Dart is not an exception. In this post, I will show you several things that you may (or may not) know about String in Dart/Flutter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. String literals can be wrapped in single quotes or double quotes.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Both are accepted in Dart
const singleQuoteString = 'Hello Coflutter';
const doubleQuoteString = "Hello Coflutter";
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;👉 It is recommended that you make it consistently, choose one style and use it throughout your code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. If you use pedantic as your linter, single quotes is preferred.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Warning with pedantic
const s1 = "Hello Coflutter"; // Warning: Only use double quotes for strings containing single quotes.
const s2 = "Hello. I'm Coflutter"; // OK
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;👉 You can find the rule &lt;a href="https://dart-lang.github.io/linter/lints/prefer_single_quotes.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Use a backslash ( \ ) to escape special characters.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("I'm Coflutter");
print("I\'m Coflutter");
print("I\'m \"Coflutter\"");
print('Path: C:\\Program Files\\Coflutter');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Output
I'm Coflutter
I'm Coflutter
I'm "Coflutter"
Path: C:\Program Files\Coflutter
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. “Raw” string (r before string) can be used to escape special character too.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// "Raw" string
print(r'Path: C:\Program Files\Coflutter');
print(r'I have $100 USD');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Output
Path: C:\Program Files\Coflutter
I have $100 USD
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Triple quotes can be used to represent multiple lines string (instead of using “new line” character (\n)).&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Multiple lines string
print(
      '''This is a multiple line string,
      created by Coflutter
      '''
);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Override toString( ) method in your object to have beautiful output when print( ).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;👉 Find &lt;a href="https://coflutter.com/dart-how-to-print-an-object/"&gt;details and example here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. String supports padding methods: paddingLeft( ) and paddingRight( ).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;👉 Find &lt;a href="https://coflutter.com/dart-how-to-print-an-object/"&gt;details and example here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. String multiplication is supported in Dart. But the string must be placed before the multiply operator (Permutation does not work).&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fire = '🔥';
  for (var i = 0; i &amp;lt;= 3; i++) {
    // final output = i * fire;
    // -&amp;gt; Error: The argument type 'String' can't be assigned to the parameter type 'num'.
    final output = fire * i;
    print(output);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;🔥
🔥🔥
🔥🔥🔥
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;9. String interpolation.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;👉 &lt;a href="https://coflutter.com/dart-interesting-facts-of-string-interpolation/"&gt;Interesting facts about String Interpolation&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dart</category>
      <category>flutter</category>
      <category>nextfunc</category>
      <category>coflutter</category>
    </item>
    <item>
      <title>Dart – Interesting facts about String Interpolation</title>
      <dc:creator>Phuc Tran</dc:creator>
      <pubDate>Sun, 16 Aug 2020 13:11:46 +0000</pubDate>
      <link>https://dev.to/thphuc/dart-interesting-facts-about-string-interpolation-40d</link>
      <guid>https://dev.to/thphuc/dart-interesting-facts-about-string-interpolation-40d</guid>
      <description>&lt;p&gt;In this post, we will learn a few interesting things about String interpolation in Dart.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Syntax:&lt;/strong&gt;&lt;br&gt;
The value of an expression can be placed inside a string using:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;${expression}&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final coflutter = 'Coflutter';
print('Hello ${coflutter}. Your name has ${coflutter.length} characters.');

// Hello Coflutter. Your name has 9 characters.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. If the expression is a single identifier (variable), the brackets ({}) can be omitted.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final coflutter = 'Coflutter';
print('Goodbye $coflutter.');

// Goodbye Coflutter.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. if..else inside the bracket&lt;/strong&gt;&lt;br&gt;
I don’t recommend this because it will make your code more difficult to read, but here I just show you what the language can do.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final password = 'password';
print('The password is ${password.length &amp;gt; 8 ? 'OK' : 'weak'}!');

// The password is weak!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Complex expression inside the brackets&lt;/strong&gt;&lt;br&gt;
We can even put a complex expression inside the brackets. In below example, we define an anonymous function to return the length of the provided string, then we call that function and pass “password” as a parameter.&lt;/p&gt;

&lt;p&gt;I also don’t recommend this since it’s hard to read your code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final password = 'password';
print('Password length is: ${((String pwd) {
    return pwd.length;
})(password)}.');

// Password length is: 8.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Object&lt;/strong&gt;&lt;br&gt;
If an object is placed inside the brackets, Dart internally calls toString() on that object. So that you don’t need to call toString() yourself.&lt;/p&gt;

&lt;p&gt;Check another blog here if you want to learn more about &lt;a href="https://coflutter.com/dart-how-to-print-an-object/"&gt;How to print an object in Dart&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student {
  final String name;
  final int age;

  Student(this.name, this.age);

  @override
  String toString() {
    return 'Student: {name: ${name}, age: ${age}}';
  }
}

final student = Student('Coflutter', 30);
print('Info: $student');

// Info: Student: {name: Coflutter, age: 30}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This post is also available on &lt;a href="https://coflutter.com/dart-interesting-facts-of-string-interpolation/"&gt;Coflutter&lt;/a&gt;, &lt;a href="https://medium.com/nextfunc/interesting-facts-of-string-interpolation-in-dart-e168ae014f1a"&gt;Medium&lt;/a&gt; and &lt;a href="https://www.linkedin.com/pulse/dart-interesting-facts-string-interpolation-phuc-tran/"&gt;Linkedin&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dart</category>
      <category>flutter</category>
      <category>coflutter</category>
      <category>stringinterpolation</category>
    </item>
  </channel>
</rss>
