网络请求组件

网络请求组件用于处理 HTTP 请求、WebSocket 连接等网络操作。

提示:选择合适的网络库可以简化开发并提高性能。
📱 渲染效果预览
GET https://api.example.com/data
200 OK
{"name": "John", "age": 25}

http

http 是 Flutter 官方提供的简单 HTTP 客户端。

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

// GET 请求
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
  print(response.body);
}

// POST 请求
final response = await http.post(
  Uri.parse('https://api.example.com/data'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'name': 'John', 'age': 25}),
);

// PUT 请求
final response = await http.put(
  Uri.parse('https://api.example.com/data/1'),
  body: jsonEncode({'name': 'Jane'}),
);

// DELETE 请求
final response = await http.delete(
  Uri.parse('https://api.example.com/data/1'),
);
📱 渲染效果预览
请求
拦截器
服务器
拦截器
响应

Dio

Dio 是一个功能强大的 HTTP 客户端,支持拦截器、取消请求等。

import 'package:dio/dio.dart';

final dio = Dio();

// 基本请求
final response = await dio.get('https://api.example.com/data');

// POST 请求
final response = await dio.post(
  'https://api.example.com/data',
  data: {'name': 'John', 'age': 25},
);

// 添加拦截器
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    print('请求: ${options.uri}');
    return handler.next(options);
  },
  onResponse: (response, handler) {
    print('响应: ${response.statusCode}');
    return handler.next(response);
  },
  onError: (error, handler) {
    print('错误: ${error.message}');
    return handler.next(error);
  },
));

// 文件上传
final formData = FormData.fromMap({
  'file': await MultipartFile.fromFile(filePath, filename: 'upload.jpg'),
});
final response = await dio.post('https://api.example.com/upload', data: formData);

GraphQL

GraphQL 用于执行 GraphQL 查询和变更。

import 'package:graphql_flutter/graphql_flutter.dart';

// 创建客户端
final HttpLink httpLink = HttpLink('https://api.example.com/graphql');

final client = ValueNotifier(
  GraphQLClient(
    link: httpLink,
    cache: GraphQLCache(store: InMemoryStore()),
  ),
);

// 查询
final QueryOptions options = QueryOptions(
  document: gql('''
    query GetUser(\$id: ID!) {
      user(id: \$id) {
        name
        email
      }
    }
  '''),
  variables: {'id': '123'},
);

final QueryResult result = await client.value.query(options);

// 变更
final MutationOptions options = MutationOptions(
  document: gql('''
    mutation CreateUser(\$name: String!, \$email: String!) {
      createUser(name: \$name, email: \$email) {
        id
        name
      }
    }
  '''),
  variables: {'name': 'John', 'email': 'john@example.com'},
);

final QueryResult result = await client.value.mutate(options);
📱 渲染效果预览
发送: Hello, WebSocket!
收到: Hello, WebSocket!
发送: How are you?
收到: How are you?

WebSocket

WebSocket 用于建立实时双向通信连接。

import 'package:web_socket_channel/web_socket_channel.dart';

// 连接 WebSocket
final channel = WebSocketChannel.connect(
  Uri.parse('wss://echo.websocket.org'),
);

// 发送消息
channel.sink.add('Hello, WebSocket!');

// 监听消息
channel.stream.listen(
  (message) {
    print('收到消息: $message');
  },
  onError: (error) {
    print('错误: $error');
  },
  onDone: () {
    print('连接关闭');
  },
);

// 关闭连接
channel.sink.close();
📱 渲染效果预览
📶
WiFi
📱
移动数据
离线

Connectivity

Connectivity 用于检测网络连接状态。

import 'package:connectivity_plus/connectivity_plus.dart';

// 检查当前连接状态
final connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
  print('使用移动数据');
} else if (connectivityResult == ConnectivityResult.wifi) {
  print('使用 WiFi');
} else if (connectivityResult == ConnectivityResult.none) {
  print('无网络连接');
}

// 监听网络变化
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
  print('网络状态变化: $result');
});
网络请求最佳实践:
  • 使用 Dio 处理复杂网络需求
  • 添加请求和响应拦截器
  • 实现错误处理和重试机制
  • 使用缓存提高性能
  • 检测网络状态提供更好的用户体验