跳转至正文

更新网络数据

如何使用 http 这个 package 来更新远程服务器的数据。

对于大部分应用来说,在网络上更新数据都是必不可少的。 http package 正好可以满足这一需求!

本教程包含以下步骤:

  1. 添加 http package。

  2. 使用 http package 在网络上更新数据。

  3. 将响应转换成一个自定义的 Dart 对象。

  4. 从互联网获取数据。

  5. 根据用户输入更新现有的 title

  6. 更新数据并在屏幕上显示响应。

1. 添加 http package

#

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

flutter pub add http

导入 http package。

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

如果你要部署 Android,请编辑 AndroidManifest.xml 文件,添加 Internet 权限。

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

同样,如果你要部署 macOS,请编辑 macos/Runner/DebugProfile.entitlementsmacos/Runner/Release.entitlements 文件,添加 network client 权限。

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

2. 使用 http package 在网络上更新数据

#

本教程介绍如何使用 http.put() 方法将相册标题更新到 JSONPlaceholder

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

使用 pattern matching 转换 JSON 只是其中一种方式。想了解更多,请查看完整文章:JSON and serialization

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 package 将响应体转换成 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.');
  }
}

太棒了!现在你就拥有了一个可以更新相册标题的函数。

从互联网获取数据

#

在更新之前,需要先从互联网获取数据。完整示例请参阅 Fetch data 教程。

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'),
    ),
  ],
);

按下 Update Data 按钮后,网络请求会以 PUT 请求将 TextField 中的数据发送到服务器。下一步会使用 _futureAlbum 变量。

5. 在屏幕上显示响应

#

要在屏幕上显示数据,请使用 FutureBuilder widget。 FutureBuilder widget 随 Flutter 提供,可让你轻松处理异步数据源。你必须提供两个参数:

  1. 你想要处理的 Future。在本例中,即 updateAlbum() 函数返回的 future。

  2. 一个 builder 函数,根据 Future 的状态(loading、success 或 error)告诉 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();
            },
          ),
        ),
      ),
    );
  }
}