Dart - Split String by Newline Using LineSplitter

This tutorial shows you how to split a String by newline in Dart using LineSplitter.

Sometimes we may need to split a String by newline. However, different system uses different line break. Carriage Return (CR, \r, 0x0D) is used on old Macintosh operating systems. UNIX based systems including Linux and Mac OS X use Line Feed (LF, \n, 0x0A), while most of non-Unix operating systems use End of Line (EOL, \r\n, 0x0D 0x0A). Therefore, good code should handle all kind of line breaks.

Fortunately Dart has a built-in feature that allows us to split a String by newline. LineSplitter, which is part of Dart's convert API, can be used to split a String by CR, LF, or CR + LF. So, we don't need to create a new function. It returns List <String>, which means we can iterate the result.

Below is an example that uses all the line breaks above along with the result.

  import 'dart:convert';
  import 'dart:core';
  
  void main() {
    StringBuffer sb = new StringBuffer();
    sb.write("aaaaa\n");
    sb.write("bbbbb\r\n");
    sb.write("ccccc   \n");
    sb.write("\n");
    sb.write("ddddd \r\n");
    sb.write("\r\n");
    sb.write('eeeee\n');
  
    String text = sb.toString();
    print("---Original---");
    print(text);
  
    LineSplitter ls = new LineSplitter();
    List<String> lines = ls.convert(text);
  
    print("---Result---");
    for (var i = 0; i < lines.length; i++) {
      print('Line $i: ${lines[i]}');
    }
  }

Below is the output of the code above

---Original---
aaaaa
bbbbb
ccccc   

ddddd 

eeeee

---Result---
Line 0: aaaaa
Line 1: bbbbb
Line 2: ccccc   
Line 3: 
Line 4: ddddd 
Line 5: 
Line 6: eeeee