1

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!

My Car
  • 4,198
  • 5
  • 17
  • 50

4 Answers4

1

The easy and best way is here.

import 'dart:convert';

void main() {
  final String list = '["a", "b", "c", "d"]';
  final List<String> finalList = List<String>.from(json.decode(list));
  print(finalList.length.toString());
}
kunj kanani
  • 324
  • 4
  • 5
  • 1
    it is worth mentioning that, although ok, this is not the recommended way. Here you already have an implicit type inference through the `List.from()`. There fore no need to explicitly typedef the variable. Also, it is recommended to use `.toList()` rather than `List.from` which is better readability. once again this is just for a bit of contextual clarification ;) – Younss AIT MOU Nov 07 '22 at 07:14
1

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.

Younss AIT MOU
  • 871
  • 7
  • 14
1

After converting your string it will return you a list, try this:

final String list = '["a", "b", "c", "d"]';
int _length = (json.decode(list) as List).length;
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
0

do you want something like this?

void main() {
  var string = 'Hello, World!';
  // make string into a list with map
  var list = string.split('').map((char) => char).toList();
  print(list);
  print(list.length);
}
George Lee
  • 814
  • 18
  • 34