Home > Back-end >  Django and Flutter wth http Plugin
Django and Flutter wth http Plugin

Time:08-18

I've created a REST API with Django and I want to use it in Fluter. I've created the endpoints and tested them; they work fine, I've also created the models in flutter. I've done the get all endpoint. I'm now struggling with how to decode the details endpoint and use it in Flutter.

Anyone's thoughts ?

CodePudding user response:

When you receive the response from API, you can use json.decode to convert the body of your request from a string to a json, and then you can parse the json to your model, like the example below:

// Model Example
class Model {
  final String name;

  Model.fromJson(dynamic json)
    : name = json['name'];
}

...
// Do the request, receive a [response]
final body = response.body;
final jsonBody = json.decode(body);
final model = Model.fromJson(jsonBody);

If you want a more detailed example, please send a piece of your code and I can explain based on your context

CodePudding user response:

It depends on what are you using if you are using http package this is an example

import 'dart:convert' as convert;

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

void main(List<String> arguments) async {
  // This example uses the Google Books API to search for books about http.
  // https://developers.google.com/books/docs/overview
  var url =
      Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});

  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse =
        convert.jsonDecode(response.body) as Map<String, dynamic>;
    var itemCount = jsonResponse['totalItems'];
    print('Number of books about http: $itemCount.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

if you are using Dio package you don't need to decode dio will do it for you this is an example

import 'package:dio/dio.dart';

void getHttp() async {
  try {
    var response = await Dio().get('http://www.google.com');
    print(response);
  } catch (e) {
    print(e);
  }
}
  • Related