Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 376
Tony Avatar asked Oct 19 '25 05:10

Tony


2 Answers

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"
like image 198
mrgnhnt96 Avatar answered Oct 22 '25 00:10

mrgnhnt96


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);
like image 37
Henok Avatar answered Oct 22 '25 00:10

Henok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!