Advertisement
binemmanuel

HttpService

Dec 14th, 2020
1,049
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.33 KB | None | 0 0
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/widgets.dart';
  4. import 'package:http/http.dart' as http;
  5. import 'package:project-name/Models/model.dart'; // Change project-name to you project name
  6.  
  7. class HttpService {
  8.   final String url;
  9.   final Map<String, dynamic> body;
  10.   var network;
  11.  
  12.   HttpService({
  13.     @required this.url,
  14.     this.body,
  15.   });
  16.  
  17.   /*
  18.    * Send a Post request
  19.    */
  20.   Future<Model> post(context) async {
  21.     try {
  22.       http.Response res = await http.post(
  23.         Uri.encodeFull(url),
  24.         headers: {
  25.           'Content-Type': 'application/json; charset=UTF-8',
  26.           'Accept': 'application/json',
  27.         },
  28.         body: jsonEncode(body),
  29.       );
  30.  
  31.       var response = jsonDecode(res.body);
  32.  
  33.       return Model.fromJson(response);
  34.     } catch (e) {
  35.       throw e;
  36.     }
  37.   }
  38.  
  39.   /*
  40.    * Send a Post request
  41.    */
  42.   // ignore: missing_return
  43.   Future<Model> getRequest() async {
  44.     try {
  45.       http.Response res = await http.get(
  46.         Uri.encodeFull(url),
  47.         headers: {
  48.           'Content-Type': 'application/json; charset=UTF-8',
  49.           'Accept': 'application/json',
  50.         },
  51.       );
  52.  
  53.       var response = jsonDecode(res.body);
  54.  
  55.       return Model.fromJson(response);
  56.     } catch (e) {
  57.       // throw e;
  58.     }
  59.   }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement