网络与存储

Flutter 教程 · 第 7 章 · 5 次浏览

Flutter 网络请求用 http 或 dio 包:get/post 请求、JSON 解析、异步加载数据到界面。dio 功能更强(拦截器、超时、上传下载),生产常用。

基本流程

  1. pubspec.yaml 加依赖:dio
  2. 定义数据模型(fromJson 解析)
  3. FutureBuilder 或手动 setState 展示数据

代码示例

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

class Product {
  final int id;
  final String name;
  final double price;

  Product({required this.id, required this.name, required this.price});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json["id"],
      name: json["name"],
      price: (json["price"] as num).toDouble(),
    );
  }
}

Future<List<Product>> fetchProducts() async {
  final res = await http.get(Uri.parse("https://api.example.com/products"));
  final data = jsonDecode(res.body) as List;
  return data.map((e) => Product.fromJson(e)).toList();
}

// 页面里用 FutureBuilder 展示
// FutureBuilder<List<Product>>(
//   future: fetchProducts(),
//   builder: (context, snapshot) {
//     if (snapshot.hasData) {
//       return ListView.builder(
//         itemCount: snapshot.data!.length,
//         itemBuilder: (_, i) => ListTile(title: Text(snapshot.data![i].name)),
//       );
//     }
//     return const Center(child: CircularProgressIndicator());
//   },
// )