📜  Flutter – 从互联网获取数据

📅  最后修改于: 2021-09-02 05:51:05             🧑  作者: Mango

在当今世界,大多数应用程序严重依赖通过 Internet 从服务器获取信息。在Flutter,此类服务由http 包提供。在本文中,我们将探讨相同的内容。

要从 Internet 获取数据,请按照以下步骤操作:

  1. 导入http包
  2. 使用 http 包发出网络请求
  3. 将响应转换为自定义Dart对象
  4. 以合适的格式显示数据

导入 http 包:

要安装 http 包,请在命令提示符中使用以下命令:

pub get

或者,如果您使用的是flutter cmd,请使用以下命令:

flutter pub get

依赖

安装完成后,将依赖添加到 pubsec.yml 文件中,如下所示:

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

请求数据:

我们可以使用http.get()方法从 JSONPlaceholder 获取示例专辑数据,如下所示:

Dart
Future fetchAlbum() {
  return http.get('https://jsonplaceholder.typicode.com/albums/1');
}


Dart
class Album {
  final int userId;
  final int id;
  final String title;
  
  Album({this.userId, this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}


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
class _MyAppState extends State {
  Future futureAlbum;
  
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }


Dart
FutureBuilder(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
  
    // spinner
    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');
  
  // Appropriate action depending upon the
  // server response
  if (response.statusCode == 200) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}
  
class Album {
  final int userId;
  final int id;
  final String title;
  
  Album({this.userId, this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() => runApp(MyApp());
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State {
  Future futureAlbum;
  
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetching Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
        ),
        body: Center(
          child: FutureBuilder(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}


转换响应:

虽然发出网络请求没什么大不了的,但处理原始响应数据可能很不方便。为了让您的生活更轻松,将原始数据(即 http.response)转换为dart对象。在这里,我们将创建一个包含 JSON 数据的 Album 类,如下所示:

Dart

class Album {
  final int userId;
  final int id;
  final String title;
  
  Album({this.userId, this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

将 http.Respone 转换为相册:

现在,按照以下步骤更新fetchAlbum()函数以返回Future

  1. 使用dart: convert 包将响应正文转换为 JSON Map。
  2. 如果服务器返回状态码为 200 的 OK 响应,则使用fromJSON()工厂方法将 JSON Map 转换为 Album。
  3. 如果服务器没有返回状态码为 200 的 OK 响应,则抛出异常。

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');
  }
}

获取数据:

现在使用fetch() 方法来获取数据,如下所示:

Dart

class _MyAppState extends State {
  Future futureAlbum;
  
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

显示数据:

使用FlutterBuilder小部件在屏幕上显示数据,如下所示:

Dart

FutureBuilder(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
  
    // spinner
    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');
  
  // Appropriate action depending upon the
  // server response
  if (response.statusCode == 200) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}
  
class Album {
  final int userId;
  final int id;
  final String title;
  
  Album({this.userId, this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() => runApp(MyApp());
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State {
  Future futureAlbum;
  
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetching Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
        ),
        body: Center(
          child: FutureBuilder(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

输出:

从互联网获取数据

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!