Search code examples
stringflutterlistdartconverters

How to convert string to list and get the length of the list in Flutter?


I want to convert a string to a list and get the length of the list. I have read this question and quoted this answer. But there is a problem, when I use the answer's code, I can only use the index to get the item, and I can't read the whole list and get the length of the list.

My code:

import 'dart:convert';
…

final String list = '["a", "b", "c", "d"]';
final dynamic final_list = json.decode(list);
print(final_list[0]); // returns "a" in the debug console

How to convert string to list and get the length of the list? I would appreciate any help. Thank you in advance!


Solution

  • Your question is a bit confusion and you might want to clarify it a bit more. Nevertheless, you can try to explicitly convert the decoded result to a List like so:

    import 'dart:convert';
    
    final String list = '["a", "b", "c", "d"]';
    final final_list = json.decode(list).toList();// convert to List
    print(final_list[0]); // returns "a" in the debug console
    print(final_list.length); // returns 4
    print(final_list); // returns: [a,b,c,d] 
    

    However, without explicit conversion, final_list should still return 4. Hence, my confusion.