Flutter时间管理或倒计时插件fw_dltime的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter时间管理或倒计时插件fw_dltime的使用

fw_dltime 插件用于计算给定文件大小的下载时间。计算下载时间所需的信息包括:

  1. 文件大小,即我们想要下载的文件大小,通常以字节(bytes)、千字节(KB)、兆字节(MB)或吉字节(GB)为单位。
  2. 当前移动设备网络的下载速度。

有了这些信息后,使用以下公式计算预计的下载时间:

Download time = file size / download speed

例如,如果我们想下载一个大小为100 MB的文件,并且我们的互联网连接速度为10 Mbps,那么我们可以这样计算下载时间:

Download time = 100 MB / 10 Mbps
Download time = 100,000,000 bytes / (10,000,000 bits/second)
Download time = 10 seconds

所以,使用10 Mbps的连接速度,下载100 MB的文件大约需要10秒。

开始使用

要使用此包,在 pubspec.yaml 文件中添加 fw_dltime 作为依赖项。

使用方法

final fwDlCalc = FwDltime(debug: true, fwFileSize: 66162476);

fwDlCalc.calculateDownloadTime(
  // 多次调用,每次传递0到100之间的百分比,
  // 在这之后会给出预计的下载时间。
  (percentage, dlSpeed, time, error) {
    if (null != error) {
      debugPrint('Error found: $error');
    }
    else if (100 == percentage) {
        debugPrint('File size: ${fwDlCalc.fwFileSize} bytes');
        debugPrint('Download Speed: ${dlSpeed}Mbps');
        debugPrint('Estimated download time: ${time}s');
    } else {
      debugPrint('Calculation progress: $percentage%');
    }
  };
),

完整示例代码

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:fw_dltime/fw_dltime.dart';

import 'firebase_options.dart';

const kBodyContainerDecoration = BoxDecoration(
  border: Border(
    top: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
  ),
);

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  final _messageController = TextEditingController();
  late AnimationController _animationController;
  late Animation _animation;
  String _fwRevision = 'CSLBL.081';
  FwDltime? _fwDltimePlugin;
  String? _error;
  double _downloadTime = 0.0;
  double _downloadSpeed = 0.0;
  String _message = '';
  int _percentage = 0;
  int _index = 0;

  [@override](/user/override)
  void initState() {
    _animationController =
        AnimationController(vsync: this, duration: const Duration(seconds: 1));

    _animation =
        CurvedAnimation(parent: _animationController, curve: Curves.easeIn);
    super.initState();

    _animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _animationController.reverse(from: 1.0);
      } else if (status == AnimationStatus.dismissed) {
        _animationController.forward();
      }
    });

    _animationController.addListener(() {
      double doubleValue = _animation.value * 5;
      int intVaue = doubleValue.toInt();
      if (intVaue == _index) return; // 刷新屏幕只有在必要时才进行!

      setState(() {
        _index = intVaue;
      });
    });
  }

  [@override](/user/override)
  void dispose() {
    _animationController.dispose();
    _fwDltimePlugin?.dispose();
    super.dispose();
  }

  calculateDownloadTime(fwRevision) async {
    _fwDltimePlugin?.dispose();
    _fwRevision = fwRevision;
    _fwDltimePlugin = FwDltime(debug: true, fwRevision: _fwRevision);

    _fwDltimePlugin?.calculateDownloadTime((percentage, dlSpeed, time, error) {
      if (!mounted || 0 == percentage) return;

      setState(() {
        _error = error;
        _percentage = percentage;
        _downloadSpeed = dlSpeed;
        _downloadTime = time;
        _message = '';
        if (0 < percentage && percentage < 100) {
          _message = 'Calculating $percentage% ...';
        }
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    Widget body = const Text('');

    if (0 < _downloadTime) {
      _animationController.stop();
      _fwDltimePlugin?.cancel();

      body = Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Download Speed: ${_downloadSpeed.toStringAsFixed(2)} Mbps'),
          Text('FW Revision: ${_fwDltimePlugin?.fwRevision ?? _fwRevision}'),
          Text('Flash file size: ${_fwDltimePlugin?.fwFileSize} bytes'),
          Text('Estimated download time: ${_downloadTime.toStringAsFixed(2)}s'),
        ],
      );
    } else {
      if (100 == _percentage) {
        // 已完成
        _animationController.stop();
      }

      body = Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (0 < _percentage && 100 > _percentage)
            const CircularProgressIndicator(strokeWidth: 10),
          const SizedBox(height: 8.0),
          Text(_message),
          Text(
            _error ?? '',
            style: const TextStyle(color: Colors.red),
          ),
        ],
      );
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('下载时间计算器'),
        ),
        body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Expanded(child: body),
              Container(
                decoration: kBodyContainerDecoration,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _messageController,
                        onChanged: (value) {
                          _fwRevision = value;
                        },
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(
                              vertical: 10.0, horizontal: 20.0),
                          hintText: _fwRevision,
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    IconButton(
                      iconSize: 50,
                      focusColor: Colors.orange.withOpacity(0.3),
                      tooltip: '计算',
                      icon: _animationController.isAnimating
                          ? Image.asset('images/wifi_$_index.png')
                          : const Icon(Icons.network_check),
                      onPressed: () {
                        _animationController.forward();
                        calculateDownloadTime(_fwRevision);
                        setState(() {
                          _error = null;
                          _message = '计算中 ...';
                          _percentage = 1;
                          _downloadTime = 0;
                        });
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter时间管理或倒计时插件fw_dltime的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter时间管理或倒计时插件fw_dltime的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用fw_dltime插件进行时间管理或倒计时的示例代码。fw_dltime是一个用于时间管理和倒计时的Flutter插件,尽管它不是官方或广泛知名的插件(请注意,具体插件的API可能会根据版本有所不同,以下代码基于假设的插件功能),但这里提供一个通用的实现思路。

首先,确保你已经在pubspec.yaml文件中添加了fw_dltime依赖:

dependencies:
  flutter:
    sdk: flutter
  fw_dltime: ^x.y.z  # 替换为实际的版本号

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

接下来,在你的Flutter项目中,你可以按照以下方式使用fw_dltime插件来实现倒计时功能:

import 'package:flutter/material.dart';
import 'package:fw_dltime/fw_dltime.dart'; // 假设这是插件的导入路径

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Time Management Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FwDltimeController _controller;
  String _timeLeft = "00:00:00";

  @override
  void initState() {
    super.initState();
    // 初始化FwDltimeController,并设置倒计时时间(例如,10分钟)
    _controller = FwDltimeController(duration: Duration(minutes: 10));
    // 监听时间变化
    _controller.addListener(() {
      setState(() {
        _timeLeft = _formatDuration(_controller.remainingTime);
      });
    });
    // 开始倒计时
    _controller.start();
  }

  @override
  void dispose() {
    // 释放资源
    _controller.dispose();
    super.dispose();
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    return '${twoDigits(duration.inHours % 24)}:${twoDigits(duration.inMinutes % 60)}:${twoDigits(duration.inSeconds % 60)}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Time Management Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Time Left: $_timeLeft',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                if (_controller.isRunning) {
                  _controller.pause();
                } else {
                  _controller.resume();
                }
              },
              child: Text(_controller.isRunning ? 'Pause' : 'Resume'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                _controller.reset();
                setState(() {
                  _timeLeft = "00:00:00";
                });
              },
              child: Text('Reset'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个FwDltimeController对象来控制倒计时。
  2. 使用_controller.addListener()方法来监听倒计时时间的变化,并在时间变化时更新UI。
  3. 提供了暂停、恢复和重置倒计时的按钮。

请注意,由于fw_dltime插件的具体API可能有所不同,上述代码中的类和方法名称(如FwDltimeController和它的方法)可能需要根据实际插件文档进行调整。如果fw_dltime插件不存在或API与假设不符,你可能需要寻找其他类似的插件或自己实现倒计时功能。

回到顶部