json to list flutter
To convert a JSON string to a list in Flutter, you can use the jsonDecode
function from the dart:convert
library. Here's an example:
import 'dart:convert';
void main() {
String jsonString = '[1, 2, 3, 4, 5]';
List<dynamic> list = jsonDecode(jsonString);
print(list); // Output: [1, 2, 3, 4, 5]
}
In this example, we have a JSON string [1, 2, 3, 4, 5]
. We use the jsonDecode
function to convert the JSON string into a list. The resulting list is stored in the list
variable. Finally, we print the list to the console.
Please note that the jsonDecode
function returns a dynamic
type, which means it can represent any JSON value. If you know the specific type of the JSON data, you can cast it to that type. For example, if you know the JSON represents a list of integers, you can cast it to List<int>
:
List<int> list = jsonDecode(jsonString).cast<int>();
This will give you a list of integers instead of a list of dynamic values.
I hope this helps! Let me know if you have any further questions.