Split String in flutter

1,714

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"
Share:
1,714
Tony
Author by

Tony

CodeforLife

Updated on December 25, 2022

Comments

  • Tony
    Tony over 1 year

    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 ?

    • Andrew Cheong
      Andrew Cheong over 3 years
      Your date is still a String. Yo should assign the return value of ::split to an array var.
    • Tony
      Tony over 3 years
      @AndrewCheong I actually reading this tutorialkart.com/dart/dart-split-string. The String will become list after using split, no?
    • Andrew Cheong
      Andrew Cheong over 3 years
      Nope, in that reference you also see it returning a list of strings.
    • Xenolion
      Xenolion over 3 years
      You are still using the same date object it is immutable use print( date.split('-')[0]);