Flutter

网络$http

从网络上获取数据

步骤:

  1. 添加 http package。

  2. 使用 http package 进行网络请求。

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

  4. 使用 Flutter 对数据进行获取和展示。

  5. 添加 http package

    要将 http package 添加到依赖中,运行 flutter pub add 命令:

    flutter pub add http
    

    导入 http package

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

    部署 Android,编辑 AndroidManifest.xml 文件,添加 Internet 权限。

<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
  1. 进行网络请求
Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
  • Future 是 Dart 用来处理异步操作的一个核心类,它通常代表一个可能的值或者将来或许会用到的错误。
  • http.Response 类包含成功的 http 请求接收到的数据。
  1. 将返回的响应转换成一个自定义的 Dart 对象

创建一个 Album

首先,创建一个包含网络请求返回数据的 Album 类,而且这个类还需要一个可以利用 json 创建 Album 的工厂构造器。

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

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

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

http.Response 转换成 Album

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');
  }
}
  1. 获取数据
class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;

  
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  // ···
}

显示数据

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

    // By default, show a loading spinner.
    return const CircularProgressIndicator();
  },
)

发起 HTTP 认证授权请求

添加 Authorization Headers

final response = await http.get(
  Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  // Send authorization headers to the backend.
  headers: {
    HttpHeaders.authorizationHeader: 'Basic your_api_token_here',
  },
);
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值