free geoip
56

Post Data to API Using Dart HTTP Package

Sending data to a REST API is a common requirement when building mobile and web applications. In Dart, this can…

Sending data to a REST API is a common requirement when building mobile and web applications. In Dart, this can be easily achieved using the http package. This tutorial will guide you through how to post data to an API using Dart, covering everything from importing dependencies to creating a complete POST request with headers and a body.

Post Data to API Using Dart

1. Add the HTTP Package

To begin, include the HTTP package in your pubspec.yaml file:

dependencies:
  http: ^0.13.5

Then run:

flutter pub get

2. Create a Dart Model Class

Define a data model that will be converted to JSON:

// models/user.dart
class User {
  final String name;
  final String email;

  User({required this.name, required this.email});

  Map<String, dynamic> toJson() => {
    'name': name,
    'email': email,
  };
}

3. Create an API Service

You can then create a service to handle the POST request:

// services/api_service.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/user.dart';

class ApiService {
  final String baseUrl = 'https://example.com/api';

  Future<http.Response> postUser(User user) async {
    final url = Uri.parse('$baseUrl/users');
    final headers = {'Content-Type': 'application/json'};
    final body = jsonEncode(user.toJson());

    final response = await http.post(url, headers: headers, body: body);
    return response;
  }
}

4. Use the Service in Main Function or UI

// main.dart
import 'package:flutter/material.dart';
import 'models/user.dart';
import 'services/api_service.dart';

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

class MyApp extends StatelessWidget {
  final ApiService apiService = ApiService();

  void sendData() async {
    User user = User(name: 'John Doe', email: 'john@example.com');
    final response = await apiService.postUser(user);
    print('Status code: ${response.statusCode}');
    print('Body: ${response.body}');
  }

  @override
  Widget build(BuildContext context) {
    sendData();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Post Data Example')),
        body: Center(child: Text('Posting Data to API...')),
      ),
    );
  }
}

Why This Matters

Mastering POST requests in Dart gives you the ability to interact with any RESTful API, from login systems to sending feedback forms. You can explore more advanced REST handling at Flutter.dev Networking Docs.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *