7

I need to parse JSON to object and use it in my app but I need to do this using dio library, but I'm new to it, can anybody help me how to use it to parse a JSON into an object, also my request need a token with it, my object will lock like this :

import 'dart:convert';

Users usersFromJson(String str) => Users.fromJson(json.decode(str));
String usersToJson(Users data) => json.encode(data.toJson());

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

  List<Datum> data;

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

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

class Datum {
  Datum({
    this.id,
    this.name,
    this.email,
    this.phone,
    this.status,
    this.images,
  });

  int id;
  String name;
  String email;
  String phone;
  String status;
  List<Image> images;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["id"],
    name: json["name"],
    email: json["email"],
    phone: json["phone"],
    status: json["status"],
    images: List<Image>.from(json["images"].map((x) => Image.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "email": email,
    "phone": phone,
    "status": status,
    "images": List<dynamic>.from(images.map((x) => x.toJson())),
  };
}

class Image {
  Image({
    this.id,
    this.url,
    this.isProfileImage,
  });

  int id;
  String url;
  int isProfileImage;

  factory Image.fromJson(Map<String, dynamic> json) => Image(
    id: json["id"],
    url: json["url"],
    isProfileImage: json["is_profile_image"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "url": url,
    "is_profile_image": isProfileImage,
  };
}

can any one help me step by step doing this using provider and dio please!

Qasem M. Zreaq
  • 139
  • 1
  • 1
  • 10

3 Answers3

11

Try something like this:

  final client = Dio();

  Future<_yourClass_> getData() async {
    final url = 'your-url';

    try {
      final response = await client.get(url);

      if (response.statusCode == 200) {
        return _yourClass_.fromJson(response.data);
      } else {
        print('${response.statusCode} : ${response.data.toString()}');
        throw response.statusCode;
      }
    } catch (error) {
      print(error);
    }
  }

... _yourClass_ data = await getData();

If you already has a token, you can add it into dio like this :

Dio()..options.headers['authorization'] = 'Bearer $token';

Of course it depends on authorization type. Also if you don't have token already, you need to make request first to obtain a token (similar as shown above) and then get token from response.data.

David Sedlář
  • 706
  • 5
  • 15
  • Then you can debug your error response in 'catch', you can get exactly what server says and with these informations you should be able to modify your api calls. Every API is different. – David Sedlář Oct 09 '20 at 15:22
  • I used this but give me a auth error request 401 Future getData() async { try { final response = await client.get(url,options: Options( headers: {HttpHeaders.authorizationHeader: $token} ), ); if (response.statusCode == 200) { print(response.data); return Users.fromJson(response.data); } else { print('${response.statusCode} : ${response.data.toString()}'); throw response.statusCode; } } catch (error) { print(error); } – Qasem M. Zreaq Oct 09 '20 at 15:51
  • Yea but you also get some response message from server and there you need to get info about what is wrong. 401 is response code from server. – David Sedlář Oct 09 '20 at 15:55
  • is it the right way like how I used dio called with token ? – Qasem M. Zreaq Oct 09 '20 at 15:57
  • Yea it is, but check it against api doc, for example our api needs token in format 'Bearer $token'. – David Sedlář Oct 12 '20 at 04:09
  • It depends on your API documentation, fxmpl our server needs token in this format ['authorization'] = 'Bearer $token' – David Sedlář Oct 20 '20 at 05:25
2
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

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

class _ContactListWidgetState extends State<ContactListWidget> {
  List<dynamic> users = [];

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

    getDio();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: ListView(
          children: users.map((e) {
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                 children: [
                Expanded(
                  flex: 4,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: CircleAvatar(
                          child: Image.network(e["avatar"]),
                        ),
                      ),
                      Flexible(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(e["name"],
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20,
                                  )),
                              Text(e["title"],maxLines: 1,overflow: TextOverflow.ellipsis,),
                              Chip(label: Text(e["role"]),),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    '\$  ${e["balance"].toString() == "null" ? "0" : e["balance"].toString()}',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }).toList(),
    ),
  ),
);
  }

  void getDio() async {
    try {
      var response = await Dio(BaseOptions(headers: {"Content-Type": 
"application/json"}))
          .get('https://mock-database-f1298.web.app/api/v1/users');
      users = response.data["users"];
      setState(() {});
    } catch (e) {
      print(e);
    }
  }
}

Sample Image

<img src="https://i.stack.imgur.com/OvIOH.png">
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 21 '21 at 04:27
2
//Here is the best solution for calling login apis and pass the parameters 
//in loginApis function 
// ignore_for_file: avoid_print

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:dio/dio.dart';
import 'package:rent_house/screens/Navigation/navBar.dart';

Future<String> loginApis({email, password, context}) async {
  // isloading:true;
  var apiURL = 'https://denga.r3therapeutsassaic.com/public/api/login';

  var formData = FormData.fromMap({
    'email': email,
    'password': password,
  });
  //final prefs = await SharedPreferences.getInstance();

  Dio dio = Dio();
  Response responce;
  try {
    responce = await dio.post(
      apiURL,
      data: formData,
    );

    print("response data " + responce.toString());

    if (responce.data['error'] == false) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Navbar()),
      );
      Fluttertoast.showToast(
          msg: "Login Successfull", backgroundColor: Colors.cyan);
    } else {
      Fluttertoast.showToast(
          msg: "Login Failed", backgroundColor: Colors.cyan);
    }
  } catch (e) {
    Fluttertoast.showToast(
        msg: "User Already exists", backgroundColor: Colors.cyan);
    return 'some thing wrong';
  }
  return '';
}
Noman Hassan
  • 239
  • 2
  • 10