A package that allows you to create code fields with customization options for Flutter. It can be useful for OTP and other verification methods.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text("CodeFields example"),
),
body: Center(
child: CodeFields(
length: codeLength,
),
),
),
);
}
Options that allow for more control:
Properties | Type | Description |
---|---|---|
length |
int | Code length. |
fieldWidth |
double | Width of each TextFormField. |
The default width is 60px. | ||
fieldHeight |
double | Height of each TextFormField. |
The default width is 60px. | ||
keyboardType |
TextInputType | Type of keyboard that shows up. |
The default keyboard type is TextInputType.number . |
||
inputDecoration |
InputDecoration | Allows you to customize the TextFormFields. |
textStyle |
TextStyle | The text style of the TextFormFields. |
margin |
EdgeInsets | The margin between each TextFormField. |
The default margin is EdgeInsets.symmetric(horizontal: 8.0) . |
||
validator |
FormFieldValidator<String> | An optional method that validates an input. Returns an error string to display if the input is invalid, or null otherwise. |
The returned value is displayed in the center of all TextFormField. | ||
onChanged |
Function(String) | The callback function that is executed when the entered code changes. Returns a string with the current code. |
onCompleted |
Function(String) | The callback function that is executed when the length of the entered code is complete. Returns a string with the current code. |
closeOnFinish |
bool | Option that closes the keyboard when the code is finished entering. The default value is true . |
autofocus |
bool | Select the first TextFormField and display the keyboard when it is built. The default value is false . |
You must change the inputDecoration property:
CodeFields(
length: 4,
inputDecoration: InputDecoration(
filled: true,
fillColor: Colors.grey.withOpacity(0.2),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(24.0),
borderSide: BorderSide(color: Colors.transparent)
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24.0),
),
),
)
String validateCode(String code){
if(code.length < 4) return "Please complete the code";
else{
bool isNumeric = int.tryParse(code) != null;
if(!isNumeric) return "Please enter a valid code";
}
return null;
}
final formKey = GlobalKey<FormState>();
Form(
key: formKey,
child: CodeFields(
length: 4,
)
)
FlatButton(
child: Text("Validate code"),
onPressed: () {
if(formKey.currentState.validate()){
formKey.currentState.save();
}
},
)
Add this to your package’s pubspec.yaml file:
dependencies:
code_fields: ^0.0.2
Install it:
$ flutter pub get
Import the package in your project:
import 'package:code_fields/code_fields.dart';
Author: federicodesia
Source Code: https://github.com/federicodesia/code_fields
#flutter #dart #mobile-apps