Skip to content

Instantly share code, notes, and snippets.

@kamranbekirovyz
Last active September 8, 2024 20:28
Show Gist options
  • Save kamranbekirovyz/0d0ef20e8189f1ad584bcb3512b36381 to your computer and use it in GitHub Desktop.
Save kamranbekirovyz/0d0ef20e8189f1ad584bcb3512b36381 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
const String _appPassword = 'flutterweb';
class PasswordProtectionOverlay extends StatefulWidget {
const PasswordProtectionOverlay({super.key});
@override
State<PasswordProtectionOverlay> createState() =>
_PasswordProtectionOverlayState();
}
class _PasswordProtectionOverlayState extends State<PasswordProtectionOverlay> {
bool? _authenticated;
bool _invalidPasslock = false;
late final TextEditingController _passwordController;
@override
void initState() {
super.initState();
_passwordController = TextEditingController();
_checkPasslock();
}
@override
void dispose() {
super.dispose();
_passwordController.dispose();
}
@override
Widget build(BuildContext context) {
if (_authenticated == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator.adaptive()),
);
}
if (_authenticated!) {
return const SizedBox.shrink();
}
return Scaffold(
body: Center(
child: SizedBox(
width: 320.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Enter password to continue',
style: TextStyle(fontSize: 20),
),
const SizedBox(height: 32.0),
TextField(
controller: _passwordController,
onSubmitted: (_) {
_submitPasslock();
},
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
suffixIcon: Icon(Icons.lock),
),
),
const SizedBox(height: 32.0),
FilledButton(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.all<Color>(
_invalidPasslock ? Colors.red : Colors.blue,
),
),
onPressed: () {
_submitPasslock();
},
child: Text(
_invalidPasslock ? 'Wrong Password' : 'Submit',
),
),
],
),
),
),
);
}
Future<void> _checkPasslock() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? cached = prefs.getString('password');
final bool valid = cached == _appPassword;
setState(() {
_authenticated = valid;
});
}
void _submitPasslock() async {
if (_passwordController.text == _appPassword) {
setState(() {
_authenticated = true;
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('password', _appPassword);
} else {
setState(() {
_invalidPasslock = true;
});
await Future.delayed(const Duration(milliseconds: 500));
setState(() {
_invalidPasslock = false;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment