Flutter/Dart: Split string by first occurrence

You can split the string, skip the first item of the list created and re-join them to a string.

In your case it would be something like:

var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim();                 // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"

The trim methods remove any unneccessary whitespaces around the first colon.


You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:

String s = "date   :   '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];

Tags:

Split

Dart