flutter-use-http-package

视觉设计 / 插画 界面 · 动效 · 设计品味 1 文件 EN 原文

Use the `http` package to execute GET, POST, PUT

Use the `http` package to execute GET, POST, PUT, or DELETE requests. Use when you need to fetch from or send data to a REST API.

说明语言:英文

来源flutteragent-plugins ↗ 查看原文件 ↗版权归原作者,请遵循原仓库许可
安装
npx skills add https://github.com/flutter/agent-plugins --skill flutter-use-http-package

需要已安装 skills CLI。也可以直接从源仓库 clone。

在星云中查看 ↗
SKILL.md 原文

name: flutter-use-http-package description: Use the http package to execute GET, POST, PUT, or DELETE requests. Use when you need to fetch from or send data to a REST API. metadata: model: models/gemini-3.1-pro-preview last_modified: Tue, 21 Apr 2026 21:36:42 GMT ---

Implementing Flutter Networking

Contents

Configuration & Permissions

Configure the environment and platform-specific permissions required for network access.

  1. Add the http package dependency via the terminal:
   flutter pub add http
  1. Import the package in your Dart files:
   import 'package:http/http.dart' as http;
  1. Configure Android permissions by adding the Internet permission to android/app/src/main/AndroidManifest.xml:
   <uses-permission android:name="android.permission.INTERNET" />
  1. Configure macOS entitlements by adding the network client key to both macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements:
   <key>com.apple.security.network.client</key>
   <true/>

Request Execution & Response Handling

Execute HTTP operations and map responses to strongly typed Dart objects.

Background Parsing

Offload expensive JSON parsing to a separate Isolate to prevent UI jank (frame drops).

Workflow: Executing Network Operations

Use the following checklist to implement and validate network operations.

Task Progress:

Examples

High-Fidelity Implementation: Fetching and Parsing in the Background

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

// 1. Top-level parsing function for Isolate
List<Photo> parsePhotos(String responseBody) {
  final parsed = (jsonDecode(responseBody) as List<Object?>)
      .cast<Map<String, Object?>>();
  return parsed.map<Photo>(Photo.fromJson).toList();
}

// 2. Network execution with background parsing
Future<List<Photo>> fetchPhotos() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/photos'),
    headers: {
      HttpHeaders.authorizationHeader: 'Bearer your_token_here',
      HttpHeaders.acceptHeader: 'application/json',
    },
  );

  if (response.statusCode == 200) {
    // Offload heavy parsing to a background isolate
    return compute(parsePhotos, response.body);
  } else {
    throw Exception('Failed to load photos. Status: ${response.statusCode}');
  }
}

// 3. Strongly typed model
class Photo {
  final int id;
  final String title;
  final String thumbnailUrl;

  const Photo({
    required this.id,
    required this.title,
    required this.thumbnailUrl,
  });

  factory Photo.fromJson(Map<String, dynamic> json) {
    return Photo(
      id: json['id'] as int,
      title: json['title'] as String,
      thumbnailUrl: json['thumbnailUrl'] as String,
    );
  }
}

// 4. UI Integration
class PhotoGallery extends StatefulWidget {
  const PhotoGallery({super.key});

  @override
  State<PhotoGallery> createState() => _PhotoGalleryState();
}

class _PhotoGalleryState extends State<PhotoGallery> {
  late Future<List<Photo>> _futurePhotos;

  @override
  void initState() {
    super.initState();
    // Initialize Future once to prevent re-fetching on rebuilds
    _futurePhotos = fetchPhotos();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Photo>>(
      future: _futurePhotos,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final photos = snapshot.data!;
          return ListView.builder(
            itemCount: photos.length,
            itemBuilder: (context, index) => ListTile(
              leading: Image.network(photos[index].thumbnailUrl),
              title: Text(photos[index].title),
            ),
          );
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        }
        
        // Default loading state
        return const Center(child: CircularProgressIndicator());
      },
    );
  }
}
同类技能
accessibilityaccessibility-complianceanimateanimate-expoanimation-performanceanimation-vocabularyanti-ui-slopapple-design
本页内容来自开源项目 flutter, 版权归原作者所有。
本站仅作技能索引与分享,所有 Skill 版权归其原作者所有。