Flutter锁屏控制插件lock_screen的使用

Flutter锁屏控制插件lock_screen的使用

简介

lock_screen 是一个用于在长时间处理任务期间锁定用户界面交互的 Flutter 小部件。通过该插件,可以轻松实现任务执行时的界面锁定,并支持自定义进度显示。


使用示例

以下是一个完整的示例代码,展示如何在 Flutter 应用中使用 lock_screen 插件。

示例代码

// example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:lock_screen/lock_screen.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) => MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorSchemeSeed: Colors.deepPurple,
          brightness: Brightness.light,
          useMaterial3: true,
          textButtonTheme: const TextButtonThemeData(
            style: ButtonStyle(
              padding: MaterialStatePropertyAll(
                EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 16,
                ),
              ),
            ),
          ),
        ),
        home: LockScreenWidget(child: const HomePage()),
      );
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    const vSpace = SizedBox(height: 32);
    return Scaffold(
      appBar: AppBar(
        title: const Text("LockScreen Demo"),
        actions: [
          IconButton(
            onPressed: () => mustNotBeClickable(context),
            icon: const Icon(Icons.handshake),
          )
        ],
      ),
      body: Center(
          child: Column(
        children: [
          const Spacer(),
          const TaskWidget(Duration(seconds: 1)),
          vSpace,
          const TaskWidget(
            Duration(seconds: 2),
            cancelable: true,
          ),
          vSpace,
          const TaskWidget(Duration(seconds: 3)),
          vSpace,
          TaskWidget(
            const Duration(seconds: 4),
            message: "4s task with custom widget",
            widget: Container(
              padding: const EdgeInsets.all(16),
              color: Colors.white,
              child: const Text("Custom widget"),
            ),
          ),
          vSpace,
          const TaskWidget(
            Duration(seconds: 5),
            cancelable: true,
          ),
          vSpace,
          const TaskWidget(
            Duration(seconds: 10),
            cancelable: true,
          ),
          const Spacer(),
          TextButton(
            onPressed: () => mustNotBeClickable(context),
            child: const Text("Locked during task execution"),
          ),
          const Spacer(),
        ],
      )),
    );
  }

  void mustNotBeClickable(BuildContext context) => ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("Can't be clicked during task execution"),
          padding: EdgeInsets.symmetric(horizontal: 32, vertical: 32),
          behavior: SnackBarBehavior.floating,
        ),
      );
}

class TaskWidget extends StatelessWidget {
  const TaskWidget(
    this.duration, {
    this.cancelable = false,
    this.widget,
    this.message,
    super.key,
  });

  final Duration duration;

  final bool cancelable;

  final Widget? widget;

  final String? message;

  [@override](/user/override)
  Widget build(BuildContext context) => TextButton(
        onPressed: () => doJob(context),
        child: Text(
          message ??
              "${duration.inSeconds}s task${cancelable ? " (cancelable)" : ""}",
        ),
      );

  void doJob(BuildContext context) async {
    // 获取 LockScreen 的实例
    final lockScreen = LockScreen.of(context);

    // 执行任务并显示锁屏
    await lockScreen.forJob(
      context,
      autoCancel: cancelable,
      operation: "${duration.inSeconds}s task",
      height: 250, // 锁屏高度
      showWidget: widget, // 自定义锁屏内容
      autoCancelText: "Annuler", // 取消按钮文本
      job: (updater) async {
        // 模拟任务执行
        var now = DateTime.now();
        final ends = now.add(duration);
        do {
          await Future.delayed(const Duration(milliseconds: 100));
          now = DateTime.now();
          final msDiff = ends.difference(now).inMilliseconds;
          updater.setProgress(1 - (msDiff / duration.inMilliseconds)); // 更新进度
          updater
              .setMessage("Countdown : ${(msDiff / 1000).toStringAsFixed(1)}s"); // 更新消息
        } while (now.isBefore(ends));
      },
    );
  }
}

更多关于Flutter锁屏控制插件lock_screen的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter锁屏控制插件lock_screen的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


lock_screen 是一个用于在 Flutter 应用中控制设备锁屏的插件。它允许你锁定和解锁设备的屏幕,以及检查当前屏幕的锁定状态。以下是如何使用 lock_screen 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 lock_screen 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  lock_screen: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入 lock_screen 插件:

import 'package:lock_screen/lock_screen.dart';

3. 使用插件

lock_screen 插件提供了几个主要的方法来控制设备的锁屏状态:

锁定屏幕

你可以使用 LockScreen.lock() 方法来锁定设备的屏幕:

void lockScreen() async {
  try {
    await LockScreen.lock();
    print("Screen locked successfully");
  } catch (e) {
    print("Failed to lock screen: $e");
  }
}

解锁屏幕

你可以使用 LockScreen.unlock() 方法来解锁设备的屏幕:

void unlockScreen() async {
  try {
    await LockScreen.unlock();
    print("Screen unlocked successfully");
  } catch (e) {
    print("Failed to unlock screen: $e");
  }
}

检查屏幕锁定状态

你可以使用 LockScreen.isLocked() 方法来检查当前屏幕是否被锁定:

void checkLockStatus() async {
  try {
    bool isLocked = await LockScreen.isLocked();
    print("Screen is locked: $isLocked");
  } catch (e) {
    print("Failed to check lock status: $e");
  }
}

4. 示例代码

以下是一个完整的示例,展示了如何使用 lock_screen 插件来锁定、解锁和检查屏幕的锁定状态:

import 'package:flutter/material.dart';
import 'package:lock_screen/lock_screen.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Lock Screen Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: lockScreen,
                child: Text('Lock Screen'),
              ),
              ElevatedButton(
                onPressed: unlockScreen,
                child: Text('Unlock Screen'),
              ),
              ElevatedButton(
                onPressed: checkLockStatus,
                child: Text('Check Lock Status'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void lockScreen() async {
    try {
      await LockScreen.lock();
      print("Screen locked successfully");
    } catch (e) {
      print("Failed to lock screen: $e");
    }
  }

  void unlockScreen() async {
    try {
      await LockScreen.unlock();
      print("Screen unlocked successfully");
    } catch (e) {
      print("Failed to unlock screen: $e");
    }
  }

  void checkLockStatus() async {
    try {
      bool isLocked = await LockScreen.isLocked();
      print("Screen is locked: $isLocked");
    } catch (e) {
      print("Failed to check lock status: $e");
    }
  }
}
回到顶部