flutterdart

Flutter: trim string after certain NUMBER of characters in dart


Say I have a string with n number of characters, but I want to trim it down to only 10 characters. (Given that at all times the string has greater that 10 characters) I don't know the contents of the string.

How to trim it in such a way?

I know how to trim it after a CERTAIN character

String s = "one.two";

//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);

But how to remove it after a CERTAIN NUMBER of characters?


Solution

  • All answers (using substring) get the first 10 UTF-16 code units, which is different than the first 10 characters because some characters consist of two code units. It is better to use the characters package:

    import 'package:characters/characters.dart';
    
    void main() {
      final str = "Hello šŸ˜€ World";
    
      print(str.substring(0, 9)); // BAD
      print(str.characters.take(9)); // GOOD
    }
    

    prints

    āžœ dart main.dart
    Hello šŸ˜€ 
    Hello šŸ˜€ W
    

    With substring you might even get half a character (which isn't valid):

    print(str.substring(0, 7)); // BAD
    print(str.characters.take(7)); // GOOD
    

    prints:

    Hello ļæ½
    Hello šŸ˜€