当前位置: 首页 > article >正文

Flutter_学习记录_网络请求的简单了解

在 Flutter 中,可以使用 http 包来发送请求。以下是一个完整的案例,展示如何通过 GET 请求获取数据并处理响应。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 http 包的依赖:
在这里插入图片描述
然后运行 flutter pub get 来安装依赖。

2. 完整代码示例

以下是一个完整的 GET 请求示例,从一个公开 API 获取数据并显示结果:

import 'dart:convert';

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

class HttpDemo extends StatelessWidget {
  const HttpDemo({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HttpDemo"),
      ),
      body: HttpDemoHome(),
    );
  }
}

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

  
  State<HttpDemoHome> createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {

  // 发起网络请求的方法
  Future<List<Post>> fetchPost() async {
    final url = Uri.parse('https://resources.ninghao.net/demo/posts.json');
    final response = await http.get(url);

    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      // 字典数组转模型数组
      List<Post> posts = responseBody["posts"].map<Post>((item) => Post.fromJson(item)).toList();
      return posts;
    } else {
      throw Exception("Fail to fetch post");
    }
  }

  
  Widget build(BuildContext context) {
    // FutureBuilder 构建页面
    return FutureBuilder(
      future: fetchPost(), 
      builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text("Loading"),
          );
        }
        final data =  snapshot.data;
        if (data != null) {
          return ListView(
            children: data.map((post) {
              return ListTile(
                title: Text(post.title),
                subtitle: Text(post.author),
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(post.imageUrl),
                ),
              );
            }).toList(),
          );
        } else {
          return Center(child: Text("暂无数据"));
        }
      }
    );
  }
}

// 新建数据模型 Post
class Post {
  final int id;
  final String title;
  final String description;
  final String author;
  final String imageUrl;

  Post({required this.id, 
        required this.title, 
        required this.description, 
        required this.author, 
        required this.imageUrl
      });

  // 字典转模型的方法
  Post.fromJson(Map json) 
    : id = json["id"],
      title = json["title"],
      description = json["description"],
      author = json["author"],
      imageUrl = json["imageUrl"];

  // 模型转字典的方法
  Map toJson() => {
    "title": title,
    "description": description
  };
}

效果图如下:
在这里插入图片描述

3. 代码说明

(1) 发送异步 GET 请求

final url = Uri.parse('https://resources.ninghao.net/demo/posts.json');
final response = await http.get(url);
  • 使用 http.get 方法发送 GET 请求。
  • await 关键字确保等待请求完成后再继续执行。

(2) 检查响应状态码

if (response.statusCode == 200) {
  // 解析数据
} else {
  // 处理错误
}
  • 如果状态码为 200,表示请求成功。
  • 如果状态码不是 200,则打印错误信息。

(3) 解析 JSON 数据

final responseBody = json.decode(response.body);
// 字典数组转模型数组
List<Post> posts = responseBody["posts"].map<Post>((item) => Post.fromJson(item)).toList();

(4) 构建页面
FutureBuilder组件来设置页面,属性futher就是设置请求的方法, builder就是设置构建页面的方法。


http://www.kler.cn/a/547537.html

相关文章:

  • 分布式 NewSQL 数据库(TiDB)
  • Linux系统常用命令用法详解
  • (LLaMa Factory)大模型训练方法--准备模型(Qwen2-0.5B)
  • 基于若依开发的工程项目管系统开源免费,用于工程项目投标、进度及成本管理的OA 办公开源系统,非常出色!
  • Jmeter+Jenkins接口压力测试持续集成
  • Unity序列化多态数组
  • 当Ollama遇上划词翻译:我的Windows本地AI服务搭建日记
  • AI知识库 - Cherry Studio
  • C++基础知识(三)之结构体、共同体、枚举、引用、函数重载
  • 答题考试系统php+uniapp
  • 天童美语:观察你的生活
  • Windows 常用程序名
  • 知识蒸馏中的“温度系数“调控策略:如何让小模型继承大模型智慧?
  • 第六天:requests库的用法
  • 【前端进阶】「全面优化前端开发流程」:利用规范化与自动化工具实现高效构建、部署与团队协作
  • java枚举类型的查找
  • 沃德校园助手系统php+uniapp
  • 【16届蓝桥杯寒假刷题营】第1期DAY4
  • HTTP的“对话”逻辑:请求与响应如何构建数据桥梁?
  • 【Linux】:网络通信