0

typical json response:

 {"data":[{"id":1,"partnerTypeId":1,"active":true,"name":"Covin - AINO UG","shortname":"Covin","firstname":null,"lastname":null,"addressId":1,"phoneId":null,"countryId":"in","email":"[email protected]","web":"www.covin.in","infos":{},"note":null,"createdAt":"2021-03-06 23:30:30","updatedAt":"2021-03-06 23:30:30","updatedBy":null},{"id":41,"partnerTypeId":100,"active":true,"name":"Tester IND","shortname":"T.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"email@tester","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:02","updatedAt":"2021-03-07 01:25:06","updatedBy":null},{"id":42,"partnerTypeId":100,"active":true,"name":"MIT Charl","shortname":"KITA Ch.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"kisa1@kol","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:42","updatedAt":"2021-03-07 01:25:08","updatedBy":null}]}

Generated podo class:

filename- partnerList.dart

// To parse this JSON data, do
//
//     final partnerList = partnerListFromMap(jsonString);

import 'dart:convert';

PartnerList partnerListFromMap(String str) => PartnerList.fromMap(json.decode(str));

String partnerListToMap(PartnerList data) => json.encode(data.toMap());

class PartnerList {
    PartnerList({
        this.data,
    });

    List<Datum> data;

    factory PartnerList.fromMap(Map<String, dynamic> json) => PartnerList(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
    );

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

class Datum {
    Datum({
        this.id,
        this.partnerTypeId,
        this.active,
        this.name,
        this.shortname,
        this.firstname,
        this.lastname,
        this.addressId,
        this.phoneId,
        this.countryId,
        this.email,
        this.web,
        this.infos,
        this.note,
        this.createdAt,
        this.updatedAt,
        this.updatedBy,
    });

    int id;
    int partnerTypeId;
    bool active;
    String name;
    String shortname;
    dynamic firstname;
    dynamic lastname;
    int addressId;
    dynamic phoneId;
    String countryId;
    String email;
    String web;
    Infos infos;
    dynamic note;
    DateTime createdAt;
    DateTime updatedAt;
    dynamic updatedBy;

    factory Datum.fromMap(Map<String, dynamic> json) => Datum(
        id: json["id"],
        partnerTypeId: json["partnerTypeId"],
        active: json["active"],
        name: json["name"],
        shortname: json["shortname"],
        firstname: json["firstname"],
        lastname: json["lastname"],
        addressId: json["addressId"] == null ? null : json["addressId"],
        phoneId: json["phoneId"],
        countryId: json["countryId"],
        email: json["email"],
        web: json["web"] == null ? null : json["web"],
        infos: Infos.fromMap(json["infos"]),
        note: json["note"],
        createdAt: DateTime.parse(json["createdAt"]),
        updatedAt: DateTime.parse(json["updatedAt"]),
        updatedBy: json["updatedBy"],
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "partnerTypeId": partnerTypeId,
        "active": active,
        "name": name,
        "shortname": shortname,
        "firstname": firstname,
        "lastname": lastname,
        "addressId": addressId == null ? null : addressId,
        "phoneId": phoneId,
        "countryId": countryId,
        "email": email,
        "web": web == null ? null : web,
        "infos": infos.toMap(),
        "note": note,
        "createdAt": createdAt.toIso8601String(),
        "updatedAt": updatedAt.toIso8601String(),
        "updatedBy": updatedBy,
    };
}

class Infos {
    Infos();

    factory Infos.fromMap(Map<String, dynamic> json) => Infos(
    );

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

related fetch class: file name - partner.api.dart

import 'partnerList.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

Future<List<PartnerList>> fetchPartner() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  final userid = prefs.getString('user_id');
  final token = prefs.getString('token');
  Map<String, String> requestHeaders = {
    'Accept': 'application/json',
    // "Content-Type": "application/x-www-form-urlencoded",        
    'Authorization': 'Bearer $token',
  };
  final response = await http.get("https://api.covin.in/partners/",
      headers: requestHeaders);

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    print(response.body);

    return partnerListFromMap(response.body);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load PartnerList');
  }
}

Now the first error I am getting:

A value of type 'PartnerList' can't be returned from the function 'fetchPartner' because it has a return type of 'Future<List<PartnerList>>'.dartreturn_of_invalid_type

how I can fix this?

update: I have modified the function partnerListfromMap like below:

List<PartnerList> partnerListFromMap(String str) => List<PartnerList>.from(json.decode(str));

String partnerListToMap(PartnerList data) => json.encode(data.toMap());

but I am getting another error now:

Exception has occurred. _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>')

3
  • You aren't returning a list of PartnerList but only one. Commented Mar 10, 2021 at 23:30
  • @MohammedAlfateh- can you tell me where I need to modify Commented Mar 10, 2021 at 23:49
  • 1
    the partnerListFromMap function make it return a list of object (List<PartnerList>) instead of only one PartnerList, and make sure when you call fetchPartner call it as a future by using await or then before passing it to a variable. Commented Mar 11, 2021 at 0:07

2 Answers 2

1

You can copy paste run full code below
Your json string is PartnerList not List<PartnerList>
You can use Future<PartnerList> and use return Future.value
code snippet

Future<PartnerList> fetchPartner() async {
    ...

    return Future.value(partnerListFromMap(response.body));

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'dart:convert';

PartnerList partnerListFromMap(String str) =>
    PartnerList.fromMap(json.decode(str));

String partnerListToMap(PartnerList data) => json.encode(data.toMap());

class PartnerList {
  PartnerList({
    this.data,
  });

  List<Datum> data;

  factory PartnerList.fromMap(Map<String, dynamic> json) => PartnerList(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
      );

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

class Datum {
  Datum({
    this.id,
    this.partnerTypeId,
    this.active,
    this.name,
    this.shortname,
    this.firstname,
    this.lastname,
    this.addressId,
    this.phoneId,
    this.countryId,
    this.email,
    this.web,
    this.infos,
    this.note,
    this.createdAt,
    this.updatedAt,
    this.updatedBy,
  });

  int id;
  int partnerTypeId;
  bool active;
  String name;
  String shortname;
  dynamic firstname;
  dynamic lastname;
  int addressId;
  dynamic phoneId;
  String countryId;
  String email;
  String web;
  Infos infos;
  dynamic note;
  DateTime createdAt;
  DateTime updatedAt;
  dynamic updatedBy;

  factory Datum.fromMap(Map<String, dynamic> json) => Datum(
        id: json["id"],
        partnerTypeId: json["partnerTypeId"],
        active: json["active"],
        name: json["name"],
        shortname: json["shortname"],
        firstname: json["firstname"],
        lastname: json["lastname"],
        addressId: json["addressId"] == null ? null : json["addressId"],
        phoneId: json["phoneId"],
        countryId: json["countryId"],
        email: json["email"],
        web: json["web"] == null ? null : json["web"],
        infos: Infos.fromMap(json["infos"]),
        note: json["note"],
        createdAt: DateTime.parse(json["createdAt"]),
        updatedAt: DateTime.parse(json["updatedAt"]),
        updatedBy: json["updatedBy"],
      );

  Map<String, dynamic> toMap() => {
        "id": id,
        "partnerTypeId": partnerTypeId,
        "active": active,
        "name": name,
        "shortname": shortname,
        "firstname": firstname,
        "lastname": lastname,
        "addressId": addressId == null ? null : addressId,
        "phoneId": phoneId,
        "countryId": countryId,
        "email": email,
        "web": web == null ? null : web,
        "infos": infos.toMap(),
        "note": note,
        "createdAt": createdAt.toIso8601String(),
        "updatedAt": updatedAt.toIso8601String(),
        "updatedBy": updatedBy,
      };
}

class Infos {
  Infos();

  factory Infos.fromMap(Map<String, dynamic> json) => Infos();

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Future<PartnerList> _future;

  Future<PartnerList> fetchPartner() async {
    String jsonString = '''
    {"data":[{"id":1,"partnerTypeId":1,"active":true,"name":"Covin - AINO UG","shortname":"Covin","firstname":null,"lastname":null,"addressId":1,"phoneId":null,"countryId":"in","email":"[email protected]","web":"www.covin.in","infos":{},"note":null,"createdAt":"2021-03-06 23:30:30","updatedAt":"2021-03-06 23:30:30","updatedBy":null},{"id":41,"partnerTypeId":100,"active":true,"name":"Tester IND","shortname":"T.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"email@tester","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:02","updatedAt":"2021-03-07 01:25:06","updatedBy":null},{"id":42,"partnerTypeId":100,"active":true,"name":"MIT Charl","shortname":"KITA Ch.","firstname":null,"lastname":null,"addressId":null,"phoneId":null,"countryId":"IN","email":"kisa1@kol","web":null,"infos":{},"note":null,"createdAt":"2021-03-06 23:32:42","updatedAt":"2021-03-07 01:25:08","updatedBy":null}]}
    ''';
    final response = http.Response(jsonString, 200);

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      print(response.body);

      return Future.value(partnerListFromMap(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load PartnerList');
    }
  }

  @override
  void initState() {
    _future = fetchPartner();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<PartnerList> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].id
                                        .toString()),
                                    Spacer(),
                                    Text(
                                      snapshot.data.data[index].name,
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am stuck with a similar issue. can you please take a look here- stackoverflow.com/q/66805193/1124993
0

Try this:

// this is correct. I think you generated this using app.quicktype.io ? Then it's correct.
PartnerList partnerListFromMap(String str) => PartnerList.fromMap(json.decode(str));


// you want the list of Datum.
Future<List<Datum>> fetchPartner() async {
  // other codes here ...
    return partnerListFromMap(response.body).data;
  // other codes here ...
}

2 Comments

type Datum is not a subtype of type PartnerList, if I am using Datum.
no code is there. The complete error is like this: type 'Datum' is not a subtype of type 'LIst<PartnerList>' see also" flutter.dev/docs/testing/errors

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.