1

I have a dynamic data from json, then I want to change it to a list variable, so i can be called that variable by the getSuggestions function. Here is the code :

static List<String> people = new List<String>();

  void getUsers() async {
    try {
      final response =
          await http.get("https://jsonplaceholder.typicode.com/users");
      var resbody = json.decode(response.body);
      var data = json.encode(resbody[0]);
      if (response.statusCode == 200) {
        setState(() {
          people = data;
        });
      } else {
        print("Error getting users.");
      }
    } catch (e) {
      print("Error getting users.");
    }
  }

  static List<String> getSuggestions(String query) {
    List<String> matches = List();
    matches.addAll(people);

    matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
    return matches;
  }```

1 Answer 1

1

update 1:

try it with

resbody.map((entry) => (entry['name'])).toList();

old

could you provide more information?. F.e. how does the json look like? Structure etc.

In most cases, json.decode already translates json arrays to flutter Lists. Lets say your response has the following structure:

{
  "date": "2019-07-18T06:14:36.276Z",
  "body": [
    {
      "amounts": [
        0,
        1,
        2,
      ],
      "name": "string",
    }
  ]
}

I would then suggest to create a class Data:

class Data {
  const Data({this.date, this.body});

  factory Data.fromJson(Map<String, dynamic> parsedJson) {
    return Data(
      date: parsedJson['date'] ,
      body: Body.fromJson(parsedJson['body'],
    );
  }

  final String date;
  final Body body;
}

and a class Body

class Body {
  const Body({this.date, this.body});
  factory Body.fromJson(Map<String, dynamic> parsedJson) {
    return Body(
      amounts: parsedJson['amounts'],
      name: parsedJson['name'] ,
    );
  }

  final List<int> amounts;
  final String name;
}

Then data = Data.fromJson(resbody); should return the Data class. And data.body.amounts should return the list.

Sign up to request clarification or add additional context in comments.

2 Comments

this is example from my json, i will take field name : jsonplaceholder.typicode.com/users
resbody.map((entry) => (entry['name'])).toList(); thats work... great !! thank you very much...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.