0

I've tried to fetch a list of teachers:

In provider Teacher I have:

Future<void> getTeachers() async {
    final String url = "http://10.0.2.2:8000/teachers/";
    try {
      final response = await http.get(url);
      final extractedData = json.encode(json.decode(response.body));
      final List<Teacher> loadedTeachers = [];

      extractedData.forEach((teacherId, teacherData) {
        loadedTeachers.add(Teacher(
          id: teacherData["uuid"],
          firstname: teacherData["firstname"],
          lastname: teacherData["lastname"],
          location: teacherData["location"],
          imageUrl: "",
          isActive: true,
          isFavorite: false,
        ));
      });
      _coaches = loadedCoaches;

 

      notifyListeners();
    } catch (error) {
      throw error;
    }
  }

But after encode the response.body, It returns back a String therefore I can't iterate through it like extractedTeachers.forEach to create an object of Teacher for each one. How should I handle this?

UPDATE: Sample of JSON

[
    {
        "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "[email protected]",
        "is_active": true,
        "profile": null
    },
]
3
  • Does this answer your question? Flutter: JSON Loop Commented Jul 6, 2020 at 21:46
  • Can you post a sample json. Commented Jul 7, 2020 at 5:11
  • @SagarAcharya I've updated the topic. Commented Jul 7, 2020 at 5:31

1 Answer 1

0

Just check out the example that I have made for you :

Below is the json you provided:

[
    {
        "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "[email protected]",
        "is_active": true,
        "profile": null
    }
]

model class for the json :

// To parse this JSON data, do
//
//     final teachers = teachersFromJson(jsonString);

import 'dart:convert';

List<Teachers> teachersFromJson(String str) => List<Teachers>.from(json.decode(str).map((x) => Teachers.fromJson(x)));

String teachersToJson(List<Teachers> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Teachers {
    Teachers({
        this.uuid,
        this.firstName,
        this.lastName,
        this.email,
        this.isActive,
        this.profile,
    });

    String uuid;
    String firstName;
    String lastName;
    String email;
    bool isActive;
    dynamic profile;

    factory Teachers.fromJson(Map<String, dynamic> json) => Teachers(
        uuid: json["uuid"],
        firstName: json["first_name"],
        lastName: json["last_name"],
        email: json["email"],
        isActive: json["is_active"],
        profile: json["profile"],
    );

    Map<String, dynamic> toJson() => {
        "uuid": uuid,
        "first_name": firstName,
        "last_name": lastName,
        "email": email,
        "is_active": isActive,
        "profile": profile,
    };
}

And below is the implementation:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Index(),
    );
  }
}

class Index extends StatefulWidget {
  @override
  _IndexState createState() => _IndexState();
}



class _IndexState extends State<Index> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Text('sample'),
    );
  }

  Future<String> fetchData() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");
  // this is using the model
    final teachers = teachersFromJson(data);
    print('This is the list of Strings ${teachers.length}');

/* "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "[email protected]",
        "is_active": true,
        "profile": null */

        // this below using using the map iteration

    List<Teacher> teacherList = List();

    final jsonResult = json.decode(data);
    jsonResult.forEach((element) {
      Teacher teacher = Teacher(
        id: element['uuid'],
        firstname: element['first_name'],
        lastname: element['last_name'],
        email: element['email'],
        isActive: element['is_active'],
        profile: element['profile'],
      );

      teacherList.add(teacher);
    });

    print('This is map iterated list for teacher ${teacherList.length}');

   
    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }



}





class Teacher {
  final String id;
  final String firstname;
  final String lastname;
  final String email;
  final bool isActive;
  final String profile;

  Teacher(
      {this.id,
      this.firstname,
      this.lastname,
      this.email,
      this.isActive,
      this.profile});
}

I have done in both ways using the model and using the map iteration just check it out and let me know if it works.

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

3 Comments

Thanks. I have problem with the code. I separated my Model as Teacher and Provider as Teachers. inside Teacher as you may guess I just return an object of Teacher, However in provider Teachers I fetch my data there. I don't write logic in my widget. When data is returning for each item in fetched data I append to the list loadedTeacher and at the end of the loop and set _teachers = loadedTeacher then call the notifyListener() to display them on my widget.
That's great. so its working now right you solved it on your own. Was my answer helpful. if not so that i can delete it. Let me know.
Yeah thank you. If someone doesn’t represent better answer I will confirm. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.