Home > OS >  Flutter: How to convert string to list and get the length of the list?
Flutter: How to convert string to list and get the length of the list?

Time:11-07

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!

CodePudding user response:

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());
}

CodePudding user response:

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.

CodePudding user response:

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;

CodePudding user response:

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);
}
  • Related