Skip to content

Instantly share code, notes, and snippets.

@adavis
Last active April 25, 2019 08:24
Show Gist options
  • Save adavis/ab7840abdef4baf68fccc032ba1725b7 to your computer and use it in GitHub Desktop.
Save adavis/ab7840abdef4baf68fccc032ba1725b7 to your computer and use it in GitHub Desktop.
Displays a pin number pad with 6 fields
import 'dart:math' show min;
import 'package:flutter/material.dart';
class UniqueId extends StatefulWidget {
const UniqueId({Key key, this.onSubmit}) : super(key: key);
final ValueChanged<String> onSubmit;
@override
_UniqueIdState createState() => _UniqueIdState();
}
class _UniqueIdState extends State<UniqueId> {
final Iterable<int> _sequence = Iterable<int>.generate(6).toList();
final List<String> _code = List<String>(6);
final List<FocusNode> _focusNodes = List<FocusNode>(6);
final List<TextEditingController> _textEditingControllers = List<TextEditingController>(6);
SizedBox _buildTextFormField(int index) {
return SizedBox(
width: 45,
height: 60,
child: TextFormField(
decoration: InputDecoration(
counterText: '',
contentPadding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
border: OutlineInputBorder(
borderSide: BorderSide(color: const Color(0xFFededed)),
),
),
maxLength: 1,
maxLines: 1,
style: TextStyle(
fontSize: 32,
),
cursorWidth: 0,
autofocus: false,
keyboardType: TextInputType.number,
focusNode: _focusNodes[index],
controller: _textEditingControllers[index],
validator: (String value) {
return value.isEmpty ? '' : null;
},
),
);
}
void _clearFields() {
for (var i in _sequence) {
_code[i] = '';
_textEditingControllers[i].clear();
}
}
@override
void initState() {
super.initState();
for (var i in _sequence) {
_code[i] = '';
_focusNodes[i] = FocusNode();
_textEditingControllers[i] = TextEditingController();
_focusNodes[i].addListener(() {
if (_focusNodes[i].hasFocus) {
_textEditingControllers[i].clear();
}
});
_textEditingControllers[i].addListener(() {
final String str = _textEditingControllers[i].text;
if (str != null && str.isNotEmpty) {
_code[i] = str;
var index = min(i + 1, 5);
if (i == 5) {
index = 0;
}
FocusScope.of(context).requestFocus(_focusNodes[index]);
final code = _code.join();
if (code.length == 6) {
widget.onSubmit(code);
_clearFields();
}
}
});
}
}
@override
void dispose() {
for (var i in _sequence) {
_focusNodes[i].dispose();
_textEditingControllers[i].dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final List<Widget> children = [];
for (var i in _sequence) {
children.add(_buildTextFormField(i));
children.add(const SizedBox(width: 8));
}
FocusScope.of(context).requestFocus(_focusNodes[0]);
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: children,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment