Using the http Package
Using the dio Package
Using chopper Package
Using graphql_flutter Package
Using the http Package
The http package is the most commonly used package for making HTTP requests in Flutter. It provides a simple way to make GET, POST, PUT, DELETE, and other types of HTTP requests.
Example
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class HttpExample extends StatefulWidget {
@override
_HttpExampleState createState() => _HttpExampleState();
}
class _HttpExampleState extends State<HttpExample> {
late Future<List<Post>> posts;
@override
void initState() {
super.initState();
posts = fetchPosts();
}
Future<List<Post>> fetchPosts() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((post) => Post.fromJson(post)).toList();
} else {
throw Exception('Failed to load posts');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HTTP Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData) {
return Center(child: Text('No data found'));
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data![index].title),
subtitle: Text(snapshot.data![index].body),
);
},
);
}
},
),
);
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(MaterialApp(home: HttpExample()));
Using the dio Package
dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, Request cancellation, File downloading, Timeout, etc.
Example
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
class DioExample extends StatefulWidget {
@override
_DioExampleState createState() => _DioExampleState();
}
class _DioExampleState extends State<DioExample> {
late Future<List<Post>> posts;
@override
void initState() {
super.initState();
posts = fetchPosts();
}
Future<List<Post>> fetchPosts() async {
Dio dio = Dio();
final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
List jsonResponse = response.data;
return jsonResponse.map((post) => Post.fromJson(post)).toList();
} else {
throw Exception('Failed to load posts');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dio Example'),
),
body: FutureBuilder<List<Post>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData) {
return Center(child: Text('No data found'));
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data![index].title),
subtitle: Text(snapshot.data![index].body),
);
},
);
}
},
),
);
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(MaterialApp(home: DioExample()));
Using chopper Package
chopper is another popular package for making HTTP requests. It provides a more structured approach by allowing you to define service interfaces.
Example
Add the chopper package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
chopper: ^3.0.4
build_runner: ^2.0.6
chopper_generator: ^3.0.6
Define a service interface:
import 'package:chopper/chopper.dart';
part 'post_api_service.chopper.dart';
@ChopperApi()
abstract class PostApiService extends ChopperService {
@Get(path: '/posts')
Future<Response<List<Post>>> getPosts();
static PostApiService create() {
final client = ChopperClient(
baseUrl: 'https://jsonplaceholder.typicode.com',
services: [_$PostApiService()],
converter: JsonConverter(),
);
return _$PostApiService(client);
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
Run the build command to generate the post_api_service.chopper.dart file
:
flutter packages pub run build_runner build
Use the service in your UI:
import 'package:flutter/material.dart';
import 'post_api_service.dart';
import 'package:chopper/chopper.dart';
class ChopperExample extends StatefulWidget {
@override
_ChopperExampleState createState() => _ChopperExampleState();
}
class _ChopperExampleState extends State<ChopperExample> {
late Future<Response<List<Post>>> posts;
@override
void initState() {
super.initState();
final postApiService = PostApiService.create();
posts = postApiService.getPosts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chopper Example'),
),
body: FutureBuilder<Response<List<Post>>>(
future: posts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData) {
return Center(child: Text('No data found'));
} else {
return ListView.builder(
itemCount: snapshot.data!.body!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data!.body![index].title),
subtitle: Text(snapshot.data!.body![index].body),
);
},
);
}
},
),
);
}
}
void main() => runApp(MaterialApp(home: ChopperExample()));
Using graphql_flutter Package
If your backend uses GraphQL, you can use the graphql_flutter package to make requests.
Example
Add the graphql_flutter package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
graphql_flutter: ^5.0.0
Initialize GraphQLClient and make a query:
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
class GraphQLExample extends StatefulWidget {
@override
_GraphQLExampleState createState() => _GraphQLExampleState();
}
class _GraphQLExampleState extends State<GraphQLExample> {
final HttpLink httpLink = HttpLink('https://api.spacex.land/graphql/');
@override
Widget build(BuildContext context) {
final client = ValueNotifier<GraphQLClient>(
GraphQLClient(
link: httpLink,
cache: GraphQLCache(store: InMemoryStore()),
),
);
return GraphQLProvider(
client: client,
child: Scaffold(
appBar: AppBar(
title: Text('GraphQL Example'),
),
body: Query(
options: QueryOptions(
document: gql(r'''
query GetLaunches {
launchesPast(limit: 5) {
mission_name
launch_date_utc
}
}
'''),
),
Top comments (0)