📜  Flutter – 使用 HTTP 获取 JSON 数据

📅  最后修改于: 2022-05-13 01:54:58.203000             🧑  作者: Mango

Flutter – 使用 HTTP 获取 JSON 数据

在本文中,我们将学习如何使用flutter中的 HTTP 包从 Internet 或 JSON 文件中获取数据。

什么是 HTTP?

HTTP 是一个可组合的、基于未来的库,用于发出 HTTP 请求。该包包含一组高级函数和类,可以轻松使用 HTTP 资源。它是多平台的,支持移动、桌面和浏览器。

执行:

我们假设您已经知道如何在Flutter中制作项目,我们将使用 vs 代码。

以下步骤是:

第1步:在Vs代码中创建一个项目,并删除默认代码。

第 2 步:在编写代码之前,只需在pubspec yaml文件中添加 HTTP 插件。

dependencies:
 http: ^0.13.3

或者你可以简单地从终端添加你的插件,只需输入这个命令,

flutter pub add http

之后运行这个命令来获取包,

flutter pub get

第3步:主要。 dart文件调用main()函数,在其中运行runApp()方法并给它一个 App (MyApp)。

第 4 步:现在创建一个名为“MyApp”的有状态小部件。有状态的小部件是在运行时改变它们的状态,并返回MaterialApp()的小部件,MaterialApp 有这么多的属性,但这里我们只使用了 2 或 3 个,使debugBanner: false ,tilte : “MyApi”和 home属性给你一个你想要的小部件,我们给它 MyApi()。

Dart
import 'package:flutter/material.dart';
import 'package:workingwithhttp2/MyApi.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
  
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "MyApi",
      debugShowCheckedModeBanner: false,
      home: MyApi(),
    );
  }
}


Dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
class MyApi extends StatefulWidget {
  MyApi({Key? key}) : super(key: key);
  
  @override
  _MyApiState createState() => _MyApiState();
}
  
class _MyApiState extends State {
   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeks for Geeks"),
      ),
      body: myApiWidget(),
    );
  }
}


Dart
Future> fetchUsers() async {
  var result =
      await http.get(Uri.parse("https://randomuser.me/api/?results=20"));
  return jsonDecode(result.body)['results'];
}


Dart
@override
void initState() {
  response = fetchUsers();
  super.initState();
}


Dart
myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTile(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}
myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTile(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}


现在让我们创建 MyApi 类,您可以在同一个文件上工作,但在这里我们在不同的文件中工作以完成不同的任务,所以我们创建一个新文件MyApi。dart

第 5 步:MyApi 中。 dart文件,创建一个有状态的小部件 MyApi 并返回脚手架。在脚手架中,有一个appBar ,在appBar中有一个标题:“Geeks for Geeks” ,在 body 中,我们有一个小部件myApiWidget()。

Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
class MyApi extends StatefulWidget {
  MyApi({Key? key}) : super(key: key);
  
  @override
  _MyApiState createState() => _MyApiState();
}
  
class _MyApiState extends State {
   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeks for Geeks"),
      ),
      body: myApiWidget(),
    );
  }
}

对于数据,我们有这个 JSON 文件。

第 6 步:现在让我们使用 HTTP 获取这些数据,创建一个fetchUsers函数,并通过 HTTP 实例调用 get函数。它返回对象列表。

Dart

Future> fetchUsers() async {
  var result =
      await http.get(Uri.parse("https://randomuser.me/api/?results=20"));
  return jsonDecode(result.body)['results'];
}

第 7 步:我们必须调用fetchUers()。但是在初始化我们的 APP 时加载数据是好的,为此,我们有一个init()方法。

Dart

@override
void initState() {
  response = fetchUsers();
  super.initState();
}

哦,太好了,我们成功获取数据,现在该显示它了。

第 8 步:创建一个myApiWidget()。

Dart

myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTile(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}
myApiWidget() {
  return FutureBuilder(
    future: response,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Column(
                children: [
                  ListTile(
                    title: Text(snapshot.data[index]['name']['title'] +
                        " " +
                        snapshot.data[index]['name']['first'] +
                        " " +
                        snapshot.data[index]['name']['last']),
                    trailing:
                        Text(snapshot.data[index]['dob']['age'].toString()),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(
                        snapshot.data[index]['picture']['large'],
                      ),
                    ),
                    subtitle: Text(snapshot.data[index]['email']),
                  )
                ],
              ),
            );
          },
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}

输出: