在当今世界,大多数应用程序严重依赖于通过 Internet 从服务器获取和更新信息。在Flutter,此类服务由 http 包提供。在本文中,我们将探讨相同的内容。
要更新 Internet 上的数据,请执行以下步骤:
- 导入http包
- 使用 http 包更新数据 t
- 将响应转换为自定义Dart对象
- 从互联网上获取数据。
- 更新并在屏幕上显示响应
导入 http 包:
要安装 http 包,请在命令提示符中使用以下命令:
pub get
或者,如果您使用的是flutter cmd,请使用以下命令:
flutter pub get
安装完成后,将依赖添加到 pubsec.yml 文件中,如下所示:
import 'package:http/http.dart' as http;
通过 Internet 更新数据:
使用http.put() 方法更新 JSONPlaceholder 中相册的标题,如下所示:
Dart
Future updateAlbum(String title) {
return http.put(
'https://jsonplaceholder.typicode.com/albums/1',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'title': title,
}),
);
}
Dart
class Album {
final int id;
final String title;
Album({this.id, this.title});
factory Album.fromJson(Map json) {
return Album(
id: json['id'],
title: json['title'],
);
}
}
Dart
Future updateAlbum(String title) async {
final http.Response response = await http.put(
'https://jsonplaceholder.typicode.com/albums',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'title': title,
}),
);
// Dispatch action depending upon
// the server response
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
Dart
Future fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
Dart
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: _controller,
decoration: InputDecoration(hintText: 'Enter Title'),
),
),
RaisedButton(
child: Text('Update Data'),
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
),
],
)
Dart
FutureBuilder(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
)
Dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
// Dispatch action depending upon
//the server response
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
Future updateAlbum(String title) async {
final http.Response response = await http.put(
'https://jsonplaceholder.typicode.com/albums/1',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'title': title,
}),
);
// parsing JSOn or throwing an exception
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to update album.');
}
}
class Album {
final int id;
final String title;
Album({this.id, this.title});
factory Album.fromJson(Map json) {
return Album(
id: json['id'],
title: json['title'],
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State {
final TextEditingController _controller = TextEditingController();
Future _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Update Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('GeeksForGeeks'),
backgroundColor: Colors.green,
),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data.title),
TextField(
controller: _controller,
decoration: InputDecoration(hintText: 'Enter Title'),
),
RaisedButton(
child: Text('Update Data'),
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
}
return CircularProgressIndicator();
},
),
),
),
);
}
}
转换响应:
虽然发出网络请求没什么大不了的,但处理原始响应数据可能很不方便。为了让您的生活更轻松,将原始数据(即 http.response)转换为dart对象。在这里,我们将创建一个包含 JSON 数据的 Album 类,如下所示:
Dart
class Album {
final int id;
final String title;
Album({this.id, this.title});
factory Album.fromJson(Map json) {
return Album(
id: json['id'],
title: json['title'],
);
}
}
将 http.Respone 转换为相册:
现在,按照以下步骤更新fetchAlbum ()函数以返回 Future
- 使用dart: convert 包将响应正文转换为 JSON Map。
- 如果服务器返回状态码为 200 的 OK 响应,则使用fromJSON () 工厂方法将 JSON Map 转换为 Album。
- 如果服务器没有返回状态码为 200 的 OK 响应,则抛出异常。
Dart
Future updateAlbum(String title) async {
final http.Response response = await http.put(
'https://jsonplaceholder.typicode.com/albums',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'title': title,
}),
);
// Dispatch action depending upon
// the server response
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
获取数据:
现在使用 fetch() 方法来获取数据,如下所示:
Dart
Future fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
通过用户输入更新现有数据:
现在为用户创建一个TextField以输入标题和一个RaisedButton以将数据发送到服务器。此外,定义一个TextEditingController以从TextField读取用户输入,如下所示:
Dart
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: _controller,
decoration: InputDecoration(hintText: 'Enter Title'),
),
),
RaisedButton(
child: Text('Update Data'),
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
),
],
)
显示数据:
使用 FlutterBuilder 小部件在屏幕上显示数据,如下所示:
Dart
FutureBuilder(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
)
完整的源代码:
Dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
// Dispatch action depending upon
//the server response
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load album');
}
}
Future updateAlbum(String title) async {
final http.Response response = await http.put(
'https://jsonplaceholder.typicode.com/albums/1',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode({
'title': title,
}),
);
// parsing JSOn or throwing an exception
if (response.statusCode == 200) {
return Album.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to update album.');
}
}
class Album {
final int id;
final String title;
Album({this.id, this.title});
factory Album.fromJson(Map json) {
return Album(
id: json['id'],
title: json['title'],
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State {
final TextEditingController _controller = TextEditingController();
Future _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Update Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('GeeksForGeeks'),
backgroundColor: Colors.green,
),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data.title),
TextField(
controller: _controller,
decoration: InputDecoration(hintText: 'Enter Title'),
),
RaisedButton(
child: Text('Update Data'),
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
}
return CircularProgressIndicator();
},
),
),
),
);
}
}
输出:
想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!