Flutter网络模拟插件http_simulator的使用

Flutter网络模拟插件http_simulator的使用

http_simulator 是一个用于开发阶段的 Flutter 插件,它可以模拟后端服务器的行为。它允许开发者通过简单的 HTTP 请求与模拟的数据进行交互,而无需实际连接到真实的后端服务。

功能特性

  • 发送 HTTP GET 请求。
  • 发送 HTTP POST 请求。
  • 模拟后端 API。
  • 内置本地存储,可作为数据库使用。

安装

在 Dart 或 Flutter 项目中安装 http_simulator

dart pub add http_simulator

或者在 Flutter 项目中运行:

flutter pub add http_simulator

这将在项目的 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  http_simulator: ^1.0.0

然后运行 dart pub getflutter pub get 来安装依赖。

使用说明

用户API

注册API:/user/register

请求示例:

{
   "id":1,
   "idNumber":"101254654",
   "fullName":"Khalid Alshehri",
   "dateOfBirth":"2022-10-10",
   "email":"demo@email.com",
   "mobile":"96650052154"
}

代码示例:

import 'package:http_simulator/http_simulator.dart';

void registerUser() async {
  final requestBody = {
    "id": 1,
    "idNumber": "101254654",
    "fullName": "Khalid Alshehri",
    "dateOfBirth": "2022-10-10",
    "email": "demo@email.com",
    "mobile": "96650052154"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/user/register"),
    body: requestBody
  );

  print('Status Code: ${response.statusCode}');
}

响应示例:

// 响应状态码:201

登录API:/user/login

请求示例:

{
   "idNumber":"tom",
   "password":"pass@123"
}

代码示例:

void loginUser() async {
  final requestBody = {
    "idNumber": "tom",
    "password": "pass@123"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/user/login"),
    body: requestBody
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// {
//   "id":1,
//   "idNumber":"101254654",
//   "fullName":"Khalid Alshehri",
//   "dateOfBirth":"2022-10-10",
//   "email":"demo@email.com",
//   "mobile":"96650052154",
//   "tasks":[
//      {
//         "id":1,
//         "name":"TASK1",
//         "points":1500,
//         "description":"TASK 1",
//         "type":"TASK 1"
//      }
//   ],
//   "badge":[
//      {
//         "id":1,
//         "name":"BADGE1",
//         "points":1500,
//         "description":"BADGE1 1",
//         "type":"BADGE1 1"
//      }
//   ]
// }

添加任务API:/user/task?taskId=#{taskId}

请求示例:

{
    "id":4, // userId
   "idNumber":"1051554145",
}

代码示例:

void addUserTask() async {
  final requestBody = {
    "id": 4,
    "idNumber": "1051554145"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/user/task?taskId=1"),
    body: requestBody
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// {
//   "id":1,
//   "idNumber":"101254654",
//   "fullName":"Khalid Alshehri",
//   "dateOfBirth":"2022-10-10",
//   "email":"demo@email.com",
//   "mobile":"96650052154",
//   "tasks":[
//      {
//         "id":1,
//         "name":"TASK1",
//         "points":1500,
//         "description":"TASK 1",
//         "type":"TASK 1"
//      }
//   ],
//   "badge":[
//      {
//         "id":1,
//         "name":"BADGE1",
//         "points":1500,
//         "description":"BADGE1 1",
//         "type":"BADGE1 1"
//      }
//   ]
// }

添加徽章API:/user/badge?badgeId=#{badgeId}

请求示例:

{
    "id":4, // userId
   "idNumber":"1051554145",
}

代码示例:

void addUserBadge() async {
  final requestBody = {
    "id": 4,
    "idNumber": "1051554145"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/user/badge?badgeId=1"),
    body: requestBody
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// {
//   "id":1,
//   "idNumber":"101254654",
//   "fullName":"Khalid Alshehri",
//   "dateOfBirth":"2022-10-10",
//   "email":"demo@email.com",
//   "mobile":"96650052154",
//   "tasks":[
//      {
//         "id":1,
//         "name":"TASK1",
//         "points":1500,
//         "description":"TASK 1",
//         "type":"TASK 1"
//      }
//   ],
//   "badge":[
//      {
//         "id":1,
//         "name":"BADGE1",
//         "points":1500,
//         "description":"BADGE1 1",
//         "type":"BADGE1 1"
//      }
//   ]
// }

投诉API

添加投诉API:/complaints

请求示例:

{
   "category":"test",
   "title":"test",
   "details":"test",
   "userId":5,
}

代码示例:

void addComplaint() async {
  final requestBody = {
    "category": "test",
    "title": "test",
    "details": "test",
    "userId": 5
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/complaints"),
    body: requestBody
  );

  print('Status Code: ${response.statusCode}');
}

// 响应示例:
// 状态码:201

获取用户投诉列表API:/complaints?userId=#{userId}

代码示例:

void getUserComplaints() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/complaints?userId=5")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// [
//    {
//       "id":1,
//       "category":"test",
//       "title":"test",
//       "details":"test",
//       "status":"test",
//       "userId":5,
//       "createdAt":"test",
//       "lastUpdatedAt":"test"
//    },
//    {
//       "id":1,
//       "category":"test",
//       "title":"test",
//       "details":"test",
//       "status":"test",
//       "userId":5,
//       "createdAt":"test",
//       "lastUpdatedAt":"test"
//    }
// ]

获取投诉详情API:/complaints/#{complaintId}

代码示例:

void getComplaintDetails() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/complaints/1")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// [
//    {
//       "id":1,
//       "category":"test",
//       "title":"test",
//       "details":"test",
//       "status":"test",
//       "userId":5,
//       "createdAt":"test",
//       "lastUpdatedAt":"test"
//    }
// ]

任务API

添加任务API:/tasks

请求示例:

{
   "name":"TASK1",
   "points":1500,
   "description":"TASK 1",
   "type":"TASK 1"
}

代码示例:

void addTask() async {
  final requestBody = {
    "name": "TASK1",
    "points": 1500,
    "description": "TASK 1",
    "type": "TASK 1"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/tasks"),
    body: requestBody
  );

  print('Status Code: ${response.statusCode}');
}

// 响应示例:
// 状态码:201

获取任务列表API:/tasks

代码示例:

void getTasksList() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/tasks")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// [
//    {
//       "id":1,
//       "name":"TASK1",
//       "points":1500,
//       "description":"TASK 1",
//       "type":"TASK 1"
//    },
//    {
//       "id":1,
//       "name":"TASK1",
//       "points":1500,
//       "description":"TASK 1",
//       "type":"TASK 1"
//    }
// ]

获取任务详情API:/tasks/#{taskId}

代码示例:

void getTaskDetails() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/tasks/1")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// {
//    "id":1,
//    "name":"TASK1",
//    "points":1500,
//    "description":"TASK 1",
//    "type":"TASK 1"
// }

徽章API

添加徽章API:/badges

请求示例:

{
   "name":"BADGE1",
   "points":1500,
   "description":"BADGE1 1",
   "type":"BADGE1 1"
}

代码示例:

void addBadge() async {
  final requestBody = {
    "name": "BADGE1",
    "points": 1500,
    "description": "BADGE1 1",
    "type": "BADGE1 1"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/badges"),
    body: requestBody
  );

  print('Status Code: ${response.statusCode}');
}

// 响应示例:
// 状态码:201

获取徽章列表API:/badges

代码示例:

void getBadgesList() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/badges")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// [
//    {
//       "id":1,
//       "name":"BADGE1",
//       "points":1500,
//       "description":"BADGE1 1",
//       "type":"BADGE1 1"
//    },
//    {
//       "id":1,
//       "name":"BADGE1",
//       "points":1500,
//       "description":"BADGE1 1",
//       "type":"BADGE1 1"
//    }
// ]

获取徽章详情API:/badges/#{badgeId}

代码示例:

void getBadgeDetails() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/badges/1")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// {
//    "id":1,
//    "name":"BADGE1",
//    "points":1500,
//    "description":"BADGE1 1",
//    "type":"BADGE1 1"
// }

优惠券API

添加优惠券API:/offers

请求示例:

{
   "category":"offer",
   "title":"offer",
   "description":"offer",
   "code":"OFFER"
}

代码示例:

void addOffer() async {
  final requestBody = {
    "category": "offer",
    "title": "offer",
    "description": "offer",
    "code": "OFFER"
  };

  final response = await HttpRoutingSimulator.post(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/offers"),
    body: requestBody
  );

  print('Status Code: ${response.statusCode}');
}

// 响应示例:
// 状态码:201

获取优惠券列表API:/offers/#{category}

代码示例:

void getOffersList() async {
  final response = await HttpRoutingSimulator.get(
    Uri.parse(HttpRoutingSimulator.BASE_URL + "/offers/offer")
  );

  if (response.statusCode == 200) {
    print('Response Body: ${response.body}');
  }
}

// 响应示例:
// [
//    {
//       "id":1,
//       "category":"offer",
//       "title":"offer",
//       "description":"offer",
//       "code":"OFFER"
//    },
//    {
//       "id":1,
//       "category":"offer",
//       "title":"offer",
//       "description":"offer",
//       "code":"OFFER"
//    }
// ]

更多关于Flutter网络模拟插件http_simulator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络模拟插件http_simulator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


http_simulator 是一个用于 Flutter 的插件,它允许你在开发过程中模拟网络请求和响应。这对于在没有实际后端服务器的情况下进行开发和测试非常有用。你可以定义预期的请求和响应,并在应用中使用这些模拟数据。

安装 http_simulator

首先,你需要将 http_simulator 添加到你的 pubspec.yaml 文件中:

dependencies:
  flutter:
    sdk: flutter
  http_simulator: ^0.1.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

使用 http_simulator

  1. 初始化 http_simulator

    main.dart 中初始化 http_simulator,并定义你想要的模拟请求和响应。

    import 'package:flutter/material.dart';
    import 'package:http_simulator/http_simulator.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      // 初始化 http_simulator
      HttpSimulator.initialize();
    
      // 添加模拟请求和响应
      HttpSimulator.addSimulation(
        Simulation(
          method: 'GET',
          url: 'https://api.example.com/data',
          response: SimulationResponse(
            statusCode: 200,
            body: '{"message": "Hello, World!"}',
          ),
        ),
      );
    
      runApp(MyApp());
    }
    
  2. 使用模拟数据进行网络请求

    在你的应用中使用 httpdio 等网络请求库进行请求,http_simulator 会拦截这些请求并返回你定义的模拟响应。

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('HTTP Simulator Example'),
            ),
            body: Center(
              child: FutureBuilder(
                future: fetchData(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return CircularProgressIndicator();
                  } else if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    return Text('Response: ${snapshot.data}');
                  }
                },
              ),
            ),
          ),
        );
      }
    
      Future<String> fetchData() async {
        final response = await http.get(Uri.parse('https://api.example.com/data'));
    
        if (response.statusCode == 200) {
          return jsonDecode(response.body)['message'];
        } else {
          throw Exception('Failed to load data');
        }
      }
    }
    
  3. 启用或禁用模拟器

    你可以在开发环境中启用模拟器,而在生产环境中禁用它:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      if (isDevelopmentMode) {
        HttpSimulator.initialize();
        HttpSimulator.addSimulation(
          Simulation(
            method: 'GET',
            url: 'https://api.example.com/data',
            response: SimulationResponse(
              statusCode: 200,
              body: '{"message": "Hello, World!"}',
            ),
          ),
        );
      }
    
      runApp(MyApp());
    }
回到顶部