Flutter lock screen widget

Flutter Lock Screen Widget

Flutter provides various widgets that can be used to create a lock screen interface in your app. These widgets allow you to implement security features like PIN code, fingerprint authentication, or pattern unlock. Let’s explore some examples of lock screen widgets in Flutter.

1. PIN Code Lock Screen

One common approach is to use a TextFormField widget in conjunction with validators to create a PIN code input field. You can customize the appearance and behavior of the widget to match your desired lock screen design. Here’s an example code snippet:

  
import 'package:flutter/material.dart';

class PinCodeLockScreen extends StatefulWidget {
  @override
  _PinCodeLockScreenState createState() => _PinCodeLockScreenState();
}

class _PinCodeLockScreenState extends State {
  String _pinCode = '';

  void _onPinCodeEntered(String pinCode) {
    // Implement validation logic here
    // e.g., compare with stored PIN code
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PIN Code Lock Screen'),
      ),
      body: Center(
        child: Column(
          children: [
            Text('Enter PIN Code:'),
            TextFormField(
              obscureText: true,
              onChanged: (value) {
                setState(() {
                  _pinCode = value;
                });
              },
              onFieldSubmitted: _onPinCodeEntered,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                _onPinCodeEntered(_pinCode);
              },
              child: Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: PinCodeLockScreen(),
  ));
}
  
  

2. Fingerprint Lock Screen

Flutter provides a plugin called local_auth that allows you to integrate fingerprint authentication into your lock screen. You can use this plugin to authenticate the user’s fingerprint and grant access to the app. Here’s an example code snippet:

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

class FingerprintLockScreen extends StatefulWidget {
  @override
  _FingerprintLockScreenState createState() => _FingerprintLockScreenState();
}

class _FingerprintLockScreenState extends State {
  LocalAuthentication _localAuthentication = LocalAuthentication();
  String _authenticationMessage = '';

  void _authenticate() async {
    bool authenticated = false;
  
    try {
      authenticated = await _localAuthentication.authenticate(
        localizedReason: 'Scan your fingerprint to unlock',
        useErrorDialogs: true,
        stickyAuth: true,
      );
    } catch (e) {
      // Handle any exceptions
    }
  
    if (mounted) {
      setState(() {
        _authenticationMessage =
            authenticated ? 'Fingerprint authenticated' : 'Authentication failed';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fingerprint Lock Screen'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(
              _authenticationMessage,
              style: TextStyle(fontSize: 18.0),
            ),
            ElevatedButton(
              onPressed: _authenticate,
              child: Text('Authenticate with Fingerprint'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: FingerprintLockScreen(),
  ));
}
  
  

3. Pattern Lock Screen

To create a pattern lock screen, you can use the flutter_gesture_detector package to detect the user’s gesture and draw a pattern on the screen. You can then compare the entered pattern with a stored pattern to grant access. Here’s an example code snippet:

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

class PatternLockScreen extends StatefulWidget {
  @override
  _PatternLockScreenState createState() => _PatternLockScreenState();
}

class _PatternLockScreenState extends State {
  List _selectedPoints = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pattern Lock Screen'),
      ),
      body: Center(
        child: Column(
          children: [
            GestureDetector(
              onPanDown: (details) {
                setState(() {
                  _selectedPoints.clear();
                });
              },
              onPanUpdate: (details) {
                RenderBox referenceBox = context.findRenderObject() as RenderBox;
                Offset localPosition = referenceBox.globalToLocal(details.globalPosition);
              
                setState(() {
                  _selectedPoints.add(localPosition);
                });
              },
              onPanEnd: (details) {
                // Implement validation logic here
                // e.g., compare with stored pattern
                setState(() {
                  _selectedPoints.clear();
                });
              },
              child: Container(
                width: 300.0,
                height: 300.0,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.black,
                    width: 2.0,
                  ),
                ),
                child: CustomPaint(
                  painter: PatternPainter(_selectedPoints),
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                // Reset or cancel the pattern lock screen
                setState(() {
                  _selectedPoints.clear();
                });
              },
              child: Text('Reset'),
            ),
          ],
        ),
      ),
    );
  }
}

class PatternPainter extends CustomPainter {
  final List points;

  PatternPainter(this.points);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 5.0;

    if (points.length > 1) {
      Path path = Path();
      path.moveTo(points[0].toDouble(), points[1].toDouble());

      for (int i = 2; i < points.length; i += 2) {
        path.lineTo(points[i].toDouble(), points[i + 1].toDouble());
      }

      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(covariant PatternPainter oldDelegate) => true;
}

void main() {
  runApp(MaterialApp(
    home: PatternLockScreen(),
  ));
}
  
  

These are just a few examples of lock screen widgets in Flutter. You can customize and enhance them as per your app’s requirements. Experiment with different widgets and packages available in Flutter to create an intuitive and secure lock screen for your app.

Leave a comment