Tony
Tony

Reputation: 2748

Split String in flutter

I using split method to split the String.

String date = "2020-10-07";
date.split("-");
print("split " + date[0]);

I expect will get 2020, but why it return 2 ?

Upvotes: 4

Views: 7588

Answers (3)

Abhinava B N
Abhinava B N

Reputation: 165

(Any String).split(Pattern) returns List<String>. Since no operation was done to change the variable (it anyhow can't store List<String>).

You are left with:

  1. Temporarily store the split as @Morgan Hunt and @Henok Suggested
  2. print("split " + date.split("-").first); (I guess you are going to return the first split)

Also data[0] -> is an operation on a string hence you are getting 0th position -> 2

Upvotes: 1

Henok
Henok

Reputation: 3383

It is 2 because there no change has been done to the variable date( the same without the split), but with split you can access the list like this below

String date = "2020-10-07";
var first = date.split("-").first;//returns the first element of the list
print("split " + first);

Upvotes: 1

mrgnhnt96
mrgnhnt96

Reputation: 3945

The reason you are getting 2 is because it is the first position (0) of the string variable date.

When you split a string, it will return a list/array.

String date = "2020-10-07";
final dateList = date.split("-");
print("split " + dateList[0]);
//expected "split 2020"

Upvotes: 3

Related Questions