Rahul Kumar Sharma
Rahul Kumar Sharma

Reputation: 44

How to add body in Flutter http request?

I am new in the flutter. And I am trying to work with APIs.

I searched on google and found the relevant code but I am not able to add the form data in API request.

import 'dart:convert';
import '../models/bill.dart';

Future<Stream<Bill>> getBills() async {
  final String url = 'https://api.punkapi.com/v2/beers';

  final client = new http.Client();
  final streamedRest = await client.send(http.Request('post', Uri.parse(url)));
  return streamedRest.stream
      .transform(utf8.decoder)
      .transform(json.decoder)
      .expand((data) => (data as List))
      .map((data) => Bill.fromJSON(data));
}

I have to pass 'mobileno'= 1234567890 in body. Please help me

Upvotes: 0

Views: 440

Answers (2)

Mir Injamamul
Mir Injamamul

Reputation: 147

import 'dart:convert';
import '../models/bill.dart';

Future<Stream<Bill>> getBills() async {
  final String url = 'https://api.punkapi.com/v2/beers';
  
  Map<String, dynamic> _queryParams = {};
  _queryParams['mobileno'] = '1234567890';

  _queryParams.addAll(filter.toQuery());

  Uri uri = Uri.parse(url).replace(queryParameters: _queryParams);
  

  final client = new http.Client();
  final streamedRest = await client.send(http.Request('post', uri));
  return streamedRest.stream
      .transform(utf8.decoder)
      .transform(json.decoder)
      .expand((data) => (data as List))
      .map((data) => Bill.fromJSON(data));
}

Upvotes: 0

Rida Rezzag
Rida Rezzag

Reputation: 3963

check this example

    Future<Album> createAlbum(String title) async {
  final http.Response response = await http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
  if (response.statusCode == 201) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(json.decode(response.body));
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

read more about it here Complete example

you can also use Dio package
A powerful Http client for Dart

Upvotes: 1

Related Questions