0

While trying to fetch data using API I didn't get the details . Instead of details I only get null. How should I solve this?

Hera is my Code .

my screen page code

    class ModuleListScreen extends StatefulWidget {
  const ModuleListScreen({Key? key}) : super(key: key);

  @override
  _ModuleListScreenState createState() => _ModuleListScreenState();
}

class _ModuleListScreenState extends State<ModuleListScreen> with HttpMixin {
 
 DatabaseHelper _dbHelper = DatabaseHelper();
  List<Item> modules = [];
  List<UserTable> userdetails = [];
  String userId = '';
  String accountId = '';

  @override
  void initState() {
    super.initState();
    _dbHelper.getAllUserData().then((value)async{
      userdetails = value;
      var response = await getmoduleList(value[0].userId.toString(),value[0].accountId.toString());
      response.forEach((element) {
        
        setState(() {
          modules.add(element);
        });
        print('Test Printing ${element.pkgSequence}');
        print('Test Printing ${modules[0].id}');
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue.shade300,
      appBar: AppBar(
        backgroundColor: Colors.pink,
        actions: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.white, width: 3),
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(50)),
                child: Padding(
                  padding: const EdgeInsets.all(5.0),
                  child: Image.asset('assets/images/icons/Back.png'),
                )),
          )
        ],
        title: Center(child: Text('Subject Name')),
        leading: Padding(
          padding: const EdgeInsets.all(5.0),
          child: Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white, width: 3),
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(50)),
              child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: Image.asset('assets/images/icons/ride.png'),
              )),
        ),
      ),
      body: Container(
        child:    
           
             ListView.builder(
                itemCount: modules.length,
                itemBuilder: (context, index) {

                  return Container(
                      height: MediaQuery.of(context).size.height / 3,
                      margin: EdgeInsets.all(3),
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.fromLTRB(
                                MediaQuery.of(context).size.height * .15,
                                5,
                                MediaQuery.of(context).size.height * .15,
                                5),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(50),
                                color: Colors.grey),
                            child: Text(modules[index].title.toString()),
                          ),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                              child: Container(
                                height: MediaQuery.of(context).size.height / 3,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey),
                                  borderRadius: BorderRadius.circular(10),
                                  color: Colors.white,
                                ),
                                child: ListView.builder(
                                    itemCount: 2,
                                    itemBuilder: (context, index) {
                                      return Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(
                                              '{article.chapter}',
                                              style: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 18,
                                                  fontWeight: FontWeight.w700),
                                            ),
                                            Image(
                                              height: 15,
                                              image: AssetImage(
                                                  'assets/images/icons/Download.png'),
                                            )
                                          ],
                                        ),
                                      );
                                    }),
                              ),
                            ),
                          )
                        ],
                      ));
                })
      ),
    );
  }
} 

My model page

class ModuleList {
    ModuleList({
        this.items,
        this.subject,
        this.grade,
    });

    List<Item>? items;
    String? subject;
    String? grade;

    factory ModuleList.fromMap(Map<String, dynamic> map) => ModuleList(
      items: map["items"] != null ? List<Item>.from(map["items"].map((x) => Item.fromMap(x))):[],
        // items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
        subject: map["subject"],
        grade: map["grade"],
    );

    Map<String, dynamic> toMap() => {
        "items": items,
        "subject": subject,
        "grade": grade,
    };
}

class Item {
  Item({
    this.sequenceno,
    this.id,
    this.chapter,
    this.title,
    this.packageDescription,
    this.ageLevel,
    this.pkgSequence,
    this.packagescors,
  });

  int? sequenceno;
  String? id;
  String? chapter;
  String? title;
  String? packageDescription;
  List<int>? ageLevel;
  String? pkgSequence;
  List<Packagescors>? packagescors;

  Item.fromMap(Map<String, dynamic> map) {
    Item(
      sequenceno: map["sequenceno"],
      id: map["_id"],
      chapter: map["chapter"],
      title: map["title"],
      packageDescription: map["package_description"],
      ageLevel: List<int>.from(map["age_level"].map((x) => x)),
      pkgSequence: map["pkg_sequence"],
      // packagescors: json["packagescors"] != null ? null : Packagescors.fromJson(json["packagescors"]),
      packagescors: map["packagescors"] != null
          ? List<Packagescors>.from(
              map["device_details"].map((x) => Packagescors.fromMap(x)))
          : [],
    );
  }

  Map<String, dynamic> toMap() => {
        "sequenceno": sequenceno,
        "_id": id,
        "chapter": chapter,
        "title": title,
        "package_description": packageDescription,
        "age_level": List<dynamic>.from(ageLevel!.map((x) => x)),
        "pkg_sequence": pkgSequence,
        "packagescors": packagescors,
      };
}


class Packagescors {
    Packagescors({
        this.score,
        this.date,
    });

    List<int>? score;
    List<String>? date;

    factory Packagescors.fromMap(Map<String, dynamic> map) => Packagescors(
        score: List<int>.from(map["score"].map((x) => x)),
        date: List<String>.from(map["date"].map((x) => x)),
    );

    Map<String, dynamic> toMap() => {
        "score": List<dynamic>.from(score!.map((x) => x)),
        "date": List<dynamic>.from(date!.map((x) => x)),
    };
}

My http_mixin code for the above model

Future<List<Item>> getmoduleList(
      String userId, String accountId) async {
      final queryParameters ={
        'subject':'Maths',
        'grade':'6'
      };  
    final response = await http
        .get(Uri.https(_baseUrl, "MY URI",queryParameters), headers: {
      'Content-Type': 'application/json',
      'user-id': userId,
      'account-id': accountId,
    });
    List <Item> jsonresponse = json.decode(response.body)['data']['items'].map<Item>((e)=>Item.fromMap(e)).toList();
    print((response.body));
    return jsonresponse;
  }

1.This is My code. Here I want to fetch data from API. Now the result I got when I fetch is null. I created the model using quick type also done some changes in the model.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
api test
  • 25
  • 5

0 Answers0