1import 'dart:async';
2import 'dart:convert';
3
4import 'package:flutter/material.dart';
5import 'package:http/http.dart' as http;
6
7Future<Album> createAlbum(String title) async {
8 final http.Response response = await http.post(
9 'https://jsonplaceholder.typicode.com/albums',
10 headers: <String, String>{
11 'Content-Type': 'application/json; charset=UTF-8',
12 },
13 body: jsonEncode(<String, String>{
14 'title': title,
15 }),
16 );
17
18 if (response.statusCode == 201) {
19 return Album.fromJson(jsonDecode(response.body));
20 } else {
21 throw Exception('Failed to create album.');
22 }
23}
24
25class Album {
26 final int id;
27 final String title;
28
29 Album({this.id, this.title});
30
31 factory Album.fromJson(Map<String, dynamic> json) {
32 return Album(
33 id: json['id'],
34 title: json['title'],
35 );
36 }
37}
38
39void main() {
40 runApp(MyApp());
41}
42
43class MyApp extends StatefulWidget {
44 MyApp({Key key}) : super(key: key);
45
46 @override
47 _MyAppState createState() {
48 return _MyAppState();
49 }
50}
51
52class _MyAppState extends State<MyApp> {
53 final TextEditingController _controller = TextEditingController();
54 Future<Album> _futureAlbum;
55
56 @override
57 Widget build(BuildContext context) {
58 return MaterialApp(
59 title: 'Create Data Example',
60 theme: ThemeData(
61 primarySwatch: Colors.blue,
62 ),
63 home: Scaffold(
64 appBar: AppBar(
65 title: Text('Create Data Example'),
66 ),
67 body: Container(
68 alignment: Alignment.center,
69 padding: const EdgeInsets.all(8.0),
70 child: (_futureAlbum == null)
71 ? Column(
72 mainAxisAlignment: MainAxisAlignment.center,
73 children: <Widget>[
74 TextField(
75 controller: _controller,
76 decoration: InputDecoration(hintText: 'Enter Title'),
77 ),
78 ElevatedButton(
79 child: Text('Create Data'),
80 onPressed: () {
81 setState(() {
82 _futureAlbum = createAlbum(_controller.text);
83 });
84 },
85 ),
86 ],
87 )
88 : FutureBuilder<Album>(
89 future: _futureAlbum,
90 builder: (context, snapshot) {
91 if (snapshot.hasData) {
92 return Text(snapshot.data.title);
93 } else if (snapshot.hasError) {
94 return Text("${snapshot.error}");
95 }
96
97 return CircularProgressIndicator();
98 },
99 ),
100 ),
101 ),
102 );
103 }
104}
105
1import 'package:flutter/material.dart';
2import 'package:http/http.dart' as http;
3
4Future<Album> createAlbum(String title) async {
5 final http.Response response = await http.post(
6 'https://jsonplaceholder.typicode.com/albums',
7 headers: <String, String>{
8 'Content-Type': 'application/json; charset=UTF-8',
9 },
10 body: jsonEncode(<String, String>{
11 'title': title,
12 }),
13 );
14
15 if (response.statusCode == 201) {
16 return Album.fromJson(jsonDecode(response.body));
17 } else {
18 throw Exception('Failed to create album.');
19 }
20}
21
22class Album {
23 final int id;
24 final String title;
25
26 Album({this.id, this.title});
27
28 factory Album.fromJson(Map<String, dynamic> json) {
29 return Album(
30 id: json['id'],
31 title: json['title'],
32 );
33 }
34}
35
36void main() {
37 runApp(MyApp());
38}
39
40class MyApp extends StatefulWidget {
41 MyApp({Key key}) : super(key: key);
42
43 @override
44 _MyAppState createState() {
45 return _MyAppState();
46 }
47}
48
49class _MyAppState extends State<MyApp> {
50 final TextEditingController _controller = TextEditingController();
51 Future<Album> _futureAlbum;
52
53 @override
54 Widget build(BuildContext context) {
55 return MaterialApp(
56 title: 'Create Data Example',
57 theme: ThemeData(
58 primarySwatch: Colors.blue,
59 ),
60 home: Scaffold(
61 appBar: AppBar(
62 title: Text('Create Data Example'),
63 ),
64 body: Container(
65 alignment: Alignment.center,
66 padding: const EdgeInsets.all(8.0),
67 child: (_futureAlbum == null)
68 ? Column(
69 mainAxisAlignment: MainAxisAlignment.center,
70 children: <Widget>[
71 TextField(
72 controller: _controller,
73 decoration: InputDecoration(hintText: 'Enter Title'),
74 ),
75 ElevatedButton(
76 child: Text('Create Data'),
77 onPressed: () {
78 setState(() {
79 _futureAlbum = createAlbum(_controller.text);
80 });
81 },
82 ),
83 ],
84 )
85 : FutureBuilder<Album>(
86 future: _futureAlbum,
87 builder: (context, snapshot) {
88 if (snapshot.hasData) {
89 return Text(snapshot.data.title);
90 } else if (snapshot.hasError) {
91 return Text("${snapshot.error}");
92 }
93
94 return CircularProgressIndicator();
95 },
96 ),
97 ),
98 ),
99 );
100 }
101}
102
1import 'package:http/http.dart' as http;
2
3var url = Uri.parse('https://example.com/whatsit/create');
4var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
5print('Response status: ${response.statusCode}');
6print('Response body: ${response.body}');
7
8print(await http.read('https://example.com/foobar.txt'));
9
1import 'package:http/http.dart' as http;
2import 'dart:convert';
3class API
4{
5//replace with your endpoint
6static String BASE_URL = 'https://some-url/api/';
7
8 static Future<List<ExampleData>> getRequest() async {
9
10 Response res = await http.get(BASE_URL+'example');
11
12 if (res.statusCode == 200) {
13 List<dynamic> body = jsonDecode(res.body);
14
15 // complete by parsing the json body return into ExampleData object and return
16 //.................
17 }
18}
19
20}
21
1var client = http.Client();
2try {
3 var uriResponse = await client.post(Uri.parse('https://example.com/whatsit/create'),
4 body: {'name': 'doodle', 'color': 'blue'});
5 print(await client.get(uriResponse.bodyFields['uri']));
6} finally {
7 client.close();
8}
9
1class UserAgentClient extends http.BaseClient {
2 final String userAgent;
3 final http.Client _inner;
4
5 UserAgentClient(this.userAgent, this._inner);
6
7 Future<http.StreamedResponse> send(http.BaseRequest request) {
8 request.headers['user-agent'] = userAgent;
9 return _inner.send(request);
10 }
11}
12