Flutter : JSON Keyless array to List

115 views Asked by At

I need to load a PHP response which is an array (with JSON format) to a Flutter List. How to code it in Flutter? Should I use dart convert?

This is my PHP response:

[
    "Butter",
    "Cheese / Keju",
    "Cream",
    "Fresh Juice",
    "Frozen Food Beef",
    "Frozen Food Chicken",
    "Frozen Food Pork",
    "Frozen Food Potatoes",
    "Frozen Food Vegetables",
    "Jam & Spread",
    "Mayonais",
    "Salad Dressing",
    "Sereal & Muesli",
    "Snack & Biscuit",
    "Sour Cream",
    "Soya Milk",
    "Whipping Cream",
    "Yogurt",
    "Yogurt Drink"
]
1

There are 1 answers

0
Didier Prophete On BEST ANSWER

Super simple. Just use the base json library.

import 'dart:convert';

// assume you got this string from a php request
String fromPhp = '[ "Butter", "Cheese / Keju", "Cream", "Fresh Juice", "Frozen Food Beef", "Frozen Food Chicken", "Frozen Food Pork", "Frozen Food Potatoes", "Frozen Food Vegetables", "Jam & Spread", "Mayonais", "Salad Dressing", "Sereal & Muesli", "Snack & Biscuit", "Sour Cream", "Soya Milk", "Whipping Cream", "Yogurt", "Yogurt Drink" ]';

// use this to convert it to a dart list of string
// note that the only tricky part is that json.decode will return
// a List<dynamic> so I am using List.from to convert it to List<String> 
List<String> dartList = List.from(json.decode(fromPhp));
print(dartList);