跳到主内容

通过互联网更新数据

如何使用 http 包通过互联网更新数据。

通过互联网更新数据对于大多数应用程序来说是必要的。http 包已经涵盖了这一点!

本示例将采取以下步骤

  1. 添加 `http` 包。
  2. 使用 http 包通过互联网更新数据。
  3. 将响应转换为自定义 Dart 对象。
  4. 从互联网获取数据。
  5. 从用户输入更新现有的 title
  6. 更新并在屏幕上显示响应。

1. 添加 `http` 包

#

要将 http 包添加为依赖项,请运行 flutter pub add

flutter pub add http

导入 `http` 包。

dart
import 'package:http/http.dart' as http;

如果你部署到 Android,请编辑 `AndroidManifest.xml` 文件以添加互联网权限。

xml
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

同样,如果你部署到 macOS,请编辑 `macos/Runner/DebugProfile.entitlements` 和 `macos/Runner/Release.entitlements` 文件以包含网络客户端授权。

xml
<!-- Required to fetch data from the internet. -->
<key>com.apple.security.network.client</key>
<true/>

2. 使用 http 包通过互联网更新数据

#

本教程介绍如何使用 JSONPlaceholderhttp.put() 方法更新专辑标题。

dart
Future<http.Response> updateAlbum(String title) {
  return http.put(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{'title': title}),
  );
}

http.put() 方法返回一个包含 ResponseFuture

  • Future 是 Dart 中用于处理异步操作的核心类。Future 对象表示将来某个时间点可用或可能发生的错误的值。
  • `http.Response` 类包含成功 http 调用接收到的数据。
  • updateAlbum() 方法接受一个参数 title,该参数被发送到服务器以更新 Album

3. 将 http.Response 转换为自定义 Dart 对象

#

虽然进行网络请求很简单,但直接处理原始的 `Future<http.Response>` 并不是很方便。为了简化开发,请将 `http.Response` 转换为 Dart 对象。

创建 Album 类

#

首先,创建一个 `Album` 类来包含网络请求中的数据。它包含一个工厂构造函数,用于从 JSON 创建 `Album` 对象。

使用 模式匹配 转换 JSON 只是一个选项。有关更多信息,请参阅关于 JSON 和序列化 的完整文章。

dart
class Album {
  final int id;
  final String title;

  const Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {'id': int id, 'title': String title} => Album(id: id, title: title),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}

将 `http.Response` 转换为 `Album` 对象

#

现在,使用以下步骤更新 updateAlbum() 函数以返回 Future<Album>

  1. 使用 `dart:convert` 包将响应体转换为 JSON `Map`。
  2. 如果服务器返回状态码为 200 的 UPDATED 响应,则使用 fromJson() 工厂方法将 JSON Map 转换为 Album
  3. 如果服务器没有返回状态码为 200 的 UPDATED 响应,则抛出异常。(即使在服务器响应为“404 Not Found”的情况下,也应抛出异常。不要返回 null。这在使用 snapshot 检查数据时非常重要,如下所示。)
dart
Future<Album> updateAlbum(String title) async {
  final response = await http.put(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{'title': title}),
  );

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to update album.');
  }
}

好极了!现在你已经拥有一个可以更新专辑标题的函数了。

从互联网获取数据

#

在更新数据之前,从互联网获取数据。有关完整示例,请参阅 获取数据 教程。

dart
Future<Album> fetchAlbum() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  );

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

理想情况下,您将在 initState 期间使用此方法设置 _futureAlbum 以从互联网获取数据。

4. 从用户输入更新现有标题

#

创建一个 TextField 来输入标题,并创建一个 ElevatedButton 来更新服务器上的数据。同时定义一个 TextEditingController 来读取 TextField 中的用户输入。

当按下 ElevatedButton 时,_futureAlbum 被设置为 updateAlbum() 方法返回的值。

dart
Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.all(8),
      child: TextField(
        controller: _controller,
        decoration: const InputDecoration(hintText: 'Enter Title'),
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          _futureAlbum = updateAlbum(_controller.text);
        });
      },
      child: const Text('Update Data'),
    ),
  ],
);

在按下 更新数据 按钮时,网络请求会将 TextField 中的数据作为 PUT 请求发送到服务器。_futureAlbum 变量将在下一步中使用。

5. 在屏幕上显示响应

#

要显示屏幕上的数据,请使用 FutureBuilder 组件。FutureBuilder 组件随 Flutter 一起提供,可以轻松地使用异步数据源。您必须提供两个参数

  1. 您想要处理的 Future。在这种情况下,是 updateAlbum() 函数返回的 future。
  2. 一个 `builder` 函数,它根据 `Future` 的状态(加载中、成功或错误)告诉 Flutter 要渲染什么。

请注意,snapshot.hasData 仅在快照包含非空数据值时才返回 true。这就是为什么即使在服务器响应为“404 Not Found”的情况下,updateAlbum 函数也应抛出异常的原因。如果 updateAlbum 返回 null,则 CircularProgressIndicator 将无限期地显示。

dart
FutureBuilder<Album>(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data!.title);
    } else if (snapshot.hasError) {
      return Text('${snapshot.error}');
    }

    return const CircularProgressIndicator();
  },
);

完整示例

#
dart
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  );

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

Future<Album> updateAlbum(String title) async {
  final response = await http.put(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{'title': title}),
  );

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to update album.');
  }
}

class Album {
  final int id;
  final String title;

  const Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {'id': int id, 'title': String title} => Album(id: id, title: title),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  late Future<Album> _futureAlbum;

  @override
  void initState() {
    super.initState();
    _futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Update Data Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text('Update Data Example')),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8),
          child: FutureBuilder<Album>(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasData) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(snapshot.data!.title),
                      TextField(
                        controller: _controller,
                        decoration: const InputDecoration(
                          hintText: 'Enter Title',
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            _futureAlbum = updateAlbum(_controller.text);
                          });
                        },
                        child: const Text('Update Data'),
                      ),
                    ],
                  );
                } else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }
              }

              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}