Flutter Error: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

0

I am currently building an app to fetch data from an API and I am trying to parse a JSON api from JSON Placeholder.

import 'dart:convert';

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

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

class CandidateProfile {
  CandidateProfile({
    this.id,
    this.firstName,
    this.lastName,
    this.username,
    this.email,
    this.password,
    this.profileImage,
    this.type,
    this.institution,
    this.levelOfEducation,
    this.completionYear,
    this.areaOfStudy,
    this.certificateEarned,
    this.description,
    this.startDate,
    this.endDate,
    this.jobTitle,
    this.responsibilities,
    this.skills,
    this.supervisorName,
    this.supervisorContact,
    this.primary,
    this.secondary,
    this.others,
    this.sex,
    this.mobile,
    this.biography,
    this.created,
    this.updated,
  });

  String id;
  String firstName;
  String lastName;
  String username;
  String email;
  String password;
  ProfileImage profileImage;
  String type;
  String institution;
  String levelOfEducation;
  String completionYear;
  String areaOfStudy;
  String certificateEarned;
  String description;
  String startDate;
  String endDate;
  String jobTitle;
  String responsibilities;
  String skills;
  String supervisorName;
  String supervisorContact;
  String primary;
  String secondary;
  String others;
  String sex;
  String mobile;
  String biography;
  String created;
  String updated;

  factory CandidateProfile.fromJson(Map<String, dynamic> json) => CandidateProfile(
    id: json["id"],
    firstName: json["firstName"],
    lastName: json["lastName"],
    username: json["username"],
    email: json["email"],
    password: json["password"],
    profileImage: ProfileImage.fromJson(json["profileImage"]),
    type: json["type"],
    institution: json["institution"],
    levelOfEducation: json["levelOfEducation"],
    completionYear: json["completionYear"],
    areaOfStudy: json["areaOfStudy"],
    certificateEarned: json["certificateEarned"],
    description: json["description"],
    startDate: json["startDate"],
    endDate: json["endDate"],
    jobTitle: json["jobTitle"],
    responsibilities: json["responsibilities"],
    skills: json["skills"],
    supervisorName: json["supervisorName"],
    supervisorContact: json["supervisorContact"],
    primary: json["primary"],
    secondary: json["secondary"],
    others: json["others"],
    sex: json["sex"],
    mobile: json["mobile"],
    biography: json["biography"],
    created: json["created"],
    updated: json["updated"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "firstName": firstName,
    "lastName": lastName,
    "username": username,
    "email": email,
    "password": password,
    "profileImage": profileImage.toJson(),
    "type": type,
    "institution": institution,
    "levelOfEducation": levelOfEducation,
    "completionYear": completionYear,
    "areaOfStudy": areaOfStudy,
    "certificateEarned": certificateEarned,
    "description": description,
    "startDate": startDate,
    "endDate": endDate,
    "jobTitle": jobTitle,
    "responsibilities": responsibilities,
    "skills": skills,
    "supervisorName": supervisorName,
    "supervisorContact": supervisorContact,
    "primary": primary,
    "secondary": secondary,
    "others": others,
    "sex": sex,
    "mobile": mobile,
    "biography": biography,
    "created": created,
    "updated": updated,
  };
}

class ProfileImage {
  ProfileImage();

  factory ProfileImage.fromJson(Map<String, dynamic> json) => ProfileImage(
  );

  Map<String, dynamic> toJson() => {
  };
}

This is the main.dart to read the json into the widget:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intern_capital/fetchapi/candidate_profile.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'drawermenu.dart';

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {

  Future<CandidateProfile> getInfo() async {
    var url = "http://free.api/some/endpoint";
    Map<String, String> headers1 = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': '00000000000000000000',
    };

    var response = await http.get(url,headers: headers1);
    if(response.statusCode == 200){
       return CandidateProfile.fromJson(json.decode(response.body)[0]);
    }else{
      throw Exception('Failed to load post');
    }

  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Color(0xffFFFFFF),
      appBar: AppBar(
        brightness: Brightness.light,
        backgroundColor: Color(0xffFFFFFF),
        elevation: 2,
        title: Text(
          'Profile',
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.settings,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pushNamed(context, '/m_settings');
            },
          )
        ],
      ),
      drawer: MainDrawer(),
      body: FutureBuilder<CandidateProfile>(
        future: getInfo(),
        // ignore: missing_return
        builder: (context, snapshot){
          if(snapshot.hasData){
            return SingleChildScrollView(
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 25.0, vertical: 20.0),
                child: Column(
                  children: <Widget>[
                    CircleAvatar(
                      radius: 60.0,
                      backgroundImage: AssetImage('images/boy-1@2x.png'),
                      backgroundColor: Colors.white,
                    ),
                    SizedBox(
                      height: 20.0,
                    ),
                    Container(
                      child: Text(
                        //'Frank Amankwaah',
                        snapshot.data.firstName,
                        //_listofvalues[0].email,
                        style: TextStyle(
                          fontSize: 25.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 38.0,
                    ),
                    Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Text(
                                  'Full Name',
                                  style: TextStyle(
                                    fontSize: 20.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 8.0,
                          ),
                          TextField(
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black54,
                            ),
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Color(0xffd5d6ed),
                              hintText: 'Daniel Doe',
                              contentPadding: const EdgeInsets.all(15.0),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                              enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 20.0,
                    ),
                    Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Text(
                                  'E-mail',
                                  style: TextStyle(
                                    fontSize: 20.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 8.0,
                          ),
                          TextField(
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black54,
                            ),
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Color(0xffd5d6ed),
                              hintText: 'userid@email.com',
                              contentPadding: const EdgeInsets.all(15.0),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                              enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 20.0,
                    ),
                    Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Text(
                                  'Mobile Number',
                                  style: TextStyle(
                                    fontSize: 20.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 8.0,
                          ),
                          TextField(
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black54,
                            ),
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Color(0xffd5d6ed),
                              hintText: '+244 444 44 44',
                              contentPadding: const EdgeInsets.all(15.0),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                              enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 20.0,
                    ),
                    Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Text(
                                  'Password',
                                  style: TextStyle(
                                    fontSize: 20.0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 8.0,
                          ),
                          TextField(
                            obscureText: true,
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.black54,
                            ),
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Color(0xffd5d6ed),
                              hintText: '***********',
                              contentPadding: const EdgeInsets.all(15.0),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                              enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                                borderRadius: BorderRadius.circular(5),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 40.0,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        FlatButton(
                          color: Color(0xff1722b2),
                          child: Text(
                            'SAVE',
                            style: TextStyle(
                              fontSize: 17,
                            ),
                          ),
                          shape: OutlineInputBorder(
                            borderSide: BorderSide(color: Color(0xff1722b2), width: 1),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          padding: EdgeInsets.all(12),
                          textColor: Colors.white,
                          onPressed: () {
                            //Navigator.pushNamed(context, '/m_add');
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          }else if(snapshot.hasError){
            return Text("${snapshot.error}");
          }
        },
      ),
    );
  }
}

Here is the JSON information im trying to fetch

[
  {
    "id": "string",
    "firstName": "string",
    "lastName": "string",
    "username": "string",
    "email": "string",
    "password": "string",
    "profileImage": {},
    "type": "string",
    "institution": "string",
    "levelOfEducation": "string",
    "completionYear": "string",
    "areaOfStudy": "string",
    "certificateEarned": "string",
    "description": "string",
    "startDate": "string",
    "endDate": "string",
    "jobTitle": "string",
    "responsibilities": "string",
    "skills": "string",
    "supervisorName": "string",
    "supervisorContact": "string",
    "primary": "string",
    "secondary": "string",
    "others": "string",
    "sex": "string",
    "mobile": "string",
    "biography": "string",
    "created": "string",
    "updated": "string"
  }
]

This is the error I'm getting:

Error type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

Can Anyone help me rectify this error. Im currently new and stacked. Thanks

android
api
flutter
dart
mobile
asked on Stack Overflow Jul 3, 2020 by Fiifi Ofori • edited Jul 3, 2020 by Fiifi Ofori

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0