free geoip
24

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dependencies:
http: ^0.13.5
dependencies: http: ^0.13.5
dependencies:
  http: ^0.13.5

Then run:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<a href="https://aliendro.id/implementing-hero-animations-in-flutter-apps/">flutter</a> pub get
<a href="https://aliendro.id/implementing-hero-animations-in-flutter-apps/">flutter</a> pub get
flutter pub get

2. Create a Dart Model Class

Define a data model that will be converted to JSON:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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,
};
}
// 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, }; }
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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;
}
}
// 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; } }
// 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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// main.dart
import 'package:flutter/material.dart';
import 'models/user.dart';
import 'services/api_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> {
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...')),
),
);
}
}
// main.dart import 'package:flutter/material.dart'; import 'models/user.dart'; import 'services/api_service.dart'; void main() { runApp(MyApp()); } class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> { 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...')), ), ); } }
// 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 *