2

Similar to this question (java), how can I get the platform-dependent line separator in Flutter?

I tried the Platform class but it doesn't seem to have it.

HII
  • 3,420
  • 1
  • 14
  • 35

1 Answers1

1

If there is no "dart-built-in way" of doing it, you can use an extension, something like:

import 'dart:io';

extension PlatformExtension on Platform {
  String get lineSeparator => Platform.isWindows
      ? '\r\n'
      : Platform.isMacOS
          ? '\r'
          : Platform.isLinux
              ? '\n'
              : '\n';
}

Then it can be used as:

String s = Platform().lineSeparator;

Update:

As jamesdlin suggested in the comment, LineSplitter can also come in handy when reading from text files.

HII
  • 3,420
  • 1
  • 14
  • 35
  • Modern macOS is a Unix-based OS and uses LF (`\n`) as a line separator. Only the old, "classic" MacOS (9 and earlier) used CR (`\r`). For modern platforms, `Platform.isWindows ? '\r\n' : '\n'` should be sufficient. Also, most of the time you shouldn't even care what the line separator is. – jamesdlin Sep 07 '22 at 05:57
  • 1
    Whoops, I was wrong about the last part of what I wrote. You normally shouldn't care about the line separator for reading (because you should use [`LineSplitter`](https://api.dart.dev/stable/dart-convert/LineSplitter-class.html)), but I don't think there's any automatic newline conversion for writes. – jamesdlin Sep 07 '22 at 07:10
  • @jamesdlin didn't know about LineSplitter, in this case I will definitely use it for reading instead, thx – HII Sep 07 '22 at 08:10