패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.0.0

slow_net_simulator

테스트 목적을 위해 다양한 네트워크 조건을 시뮬레이션하는 Flutter 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
10
좋아요
7
Pub 점수
150

패키지 설치

flutter pub add slow_net_simulator

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

실제 세계 시나리오에서 앱의 동작을 테스트하기 위해 느린 연결, 높은 지연 시간 및 패킷 손실과 같은 다양한 네트워크 조건을 시뮬레이션하도록 설계된 Flutter 패키지입니다. 개발자들이 물리적 장치나 복잡한 설정 없이도 애플리케이션의 성능, 사용자 경험 및 회복력을 다양한 네트워크 환경에서 평가할 수 있도록 합니다. 이 패키지는 Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼을 지원하여 크로스플랫폼 개발에 유용합니다. 앱의 강건성을 향상시키려는 QA 팀과 개발자에게 이상적입니다.

사용 사례

  • 나쁜 네트워크 조건에서 앱 성능 테스트
  • 개발 중에 실제 세계의 연결 문제를 시뮬레이션하는 것
  • 네트워크 지연 중 UI 반응성 검증
  • 시뮬레이션된 패킷 손실을 통한 데이터 무결성 보장
  • 저대역폭 환경에서 사용자 경험 향상

주요 기능

  • 사용자 정의 가능한 네트워크 속도 및 지연을 지원
  • 패킷 손실 및 연결 끊김을 시뮬레이션합니다
  • 크로스 플랫폼 호환성
  • pub.dev를 통한 간편한 통합
  • 실시간 네트워크 상태 조정
  • 최소한의 설정 필요

적합한 대상

  • 모바일 및 웹 앱 개발자
  • QA 엔지니어가 네트워크 회복력을 테스트하고 있습니다
  • 저연결 지역용 앱을 개발하는 팀
  • 네트워크 스트레스 하에서 사용자 경험에 집중하는 개발자
  • 오프라인 또는 저하 모드 처리가 필요한 응용 프로그램

고려 사항

  • 생산 환경 사용을 위한 것이 아님
  • 디버깅 성능에 영향을 줄 수 있습니다
  • 오류 탐지 방지를 위해 신중한 구성이 필요합니다
  • 시뮬레이션에 국한됨; 실제 네트워크 하드웨어를 복제하지 않음
  • 통제된 테스트 환경에서 가장 잘 사용됩니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

SlowNetSimulator

SlowNetSimulator is a powerful Flutter package designed to help developers simulate different network speeds and conditions directly within their Flutter apps. This is especially useful for testing how your app behaves under various network conditions, such as 2G, 3G, 4G, or when there is a chance of network failures.

Features

  • Simulate different network speeds: GPRS (2G), EDGE (2G), HSPA (3G), and LTE (4G).
  • Introduce artificial latency to mimic real-world conditions.
  • Configure network failure probabilities to test error handling.
  • Easily integrate with any asynchronous request.
  • Real-time adjustment of network settings via an overlay button.
  • Useful for debugging and testing app resilience.

Getting Started

To use this package, add slow_net_simulator as a dependency in your pubspec.yaml file:

dependencies:
  slow_net_simulator: ^1.0.0

Then run:

flutter pub get

Usage

1. Configuration in main.dart

In your main function, configure the simulator with a predefined network speed and failure probability:

void main() {
  SlowNetSimulator.configure(
    speed: NetworkSpeed.EDGE_2G, // Choose a predefined speed or custom speed
    failureProbability: 0.2,    // 20% chance of failure
  );

  runApp(MyApp());
}
2. Wrapping Requests with simulate

To simulate network behavior for any asynchronous request, wrap your request inside SlowNetSimulator.simulate. This works not only with Dio but also with any async operation:

final response = await SlowNetSimulator.simulate(() async {
  return await dio.get('https://jsonplaceholder.typicode.com/posts/1');
});

You can replace the dio.get call with any other request or async operation:

final result = await SlowNetSimulator.simulate(() async {
  // Perform any async task here
  return await someAsyncFunction();
});
3. Adjusting Failure Probability

The failure probability parameter allows you to define the likelihood of a request failing. This is useful for testing how your app handles sudden request failures. For example:

SlowNetSimulator.configure(
  speed: NetworkSpeed.HSPA_3G, // Simulating 3G speed
  failureProbability: 0.5,    // 50% chance of failure
);

With this setup, you can test your app's error handling capabilities and ensure it behaves gracefully under adverse conditions.

4. Show the Overlay Button

To enable the real-time adjustment of network conditions, you must ensure the overlay button is displayed on the screen. Place the following code at the top of your **build** method in your main widget or any widget where you want the overlay to appear:

@override
Widget build(BuildContext context) {

  //-----to show overlay button---------------------
  WidgetsBinding.instance.addPostFrameCallback((_) {
    SlowNetOverlay.showOverlay(context);
  });

  return MaterialApp(
    home: ExamplePage(),
  );
}
5. Example UI Integration

Below is an example of how to integrate the SlowNetSimulator with a Flutter app:

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:slow_net_simulator/slow_net_simulator.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const ExamplePage(),
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );
  }
}

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

  @override
  _ExamplePageState createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage> {
  double failureProbability = 0.0;
  NetworkSpeed speed = NetworkSpeed.HSPA_3G;
  Post? _data;
  String? errorResponse;
  bool _isLoading = false;
  bool _isSuccess = false;
  final Dio dio = Dio();

  @override
  void initState() {
    super.initState();
    _configureSimulator(NetworkSpeed.HSPA_3G, 0.0);
  }

  void _configureSimulator(NetworkSpeed speed, double failureProbability) {
    SlowNetSimulator.configure(
        speed: speed, failureProbability: failureProbability);
    setState(() {});
  }

  Future<void> _fetchData() async {
    setState(() => _isLoading = true);

    try {
      final response = await SlowNetSimulator.simulate(() async {
        return await dio.get('https://jsonplaceholder.typicode.com/posts/1');
      });

      setState(() {
        _data = Post.fromJson(response.data);
        _isSuccess = true;
        errorResponse = null;
      });
    } catch (e) {
      setState(() {
        errorResponse = e.toString();
        _isSuccess = false;
      });
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      SlowNetOverlay.showOverlay(context);
    });

    return Scaffold(
      appBar: AppBar(
        title: const Text('SlowNetSimulator Example'),
        backgroundColor: Colors.red,
        foregroundColor: Colors.white,
      ),
      body: SafeArea(
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child: _buildResponseDisplay()),
              _buildFetchButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResponseDisplay() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    } else if (!_isSuccess && errorResponse != null) {
      return Center(
        child: Container(
          height: 100,
          width: 300,
          padding: EdgeInsets.all(10),
          color: Colors.red[100],
          child: Column(
            children: [
              Icon(
                Icons.error_rounded,
                color: Colors.red[500],
                size: 45,
              ),
              Text(
                errorResponse!,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16, color: Colors.red[500]),
              ),
            ],
          ),
        ),
      );
    } else if (_data != null) {
      return SizedBox(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "Post Detail",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Text(
              _data!.title,
              style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
            ),
            Text(
              _data!.body,
              style: const TextStyle(fontSize: 16),
            ),
          ],
        ),
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  Widget _buildFetchButton() {
    return ElevatedButton(
      autofocus: false,
      style: ButtonStyle(
          backgroundColor: WidgetStatePropertyAll(Colors.red),
          foregroundColor: WidgetStatePropertyAll(Colors.white)),
      onPressed: _isLoading ? null : _fetchData,
      child: const Text('Fetch Data'),
    );
  }
}

class Post {
  final int id;
  final String title;
  final String body;

  Post({required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json["id"],
      title: json["title"],
      body: json["body"],
    );
  }
}

  • This package is ideal for developers who work on both the backend and mobile side and want to test app behavior under simulated network conditions.

Contributing

Contributions are welcome! If you encounter issues or have feature requests, please open an issue or submit a pull request on the slow_net_simulator repository.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Package on Pub.dev

Find this package on Pub.dev: slow_net_simulator

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.