How can I update the PinInput Boxes with input from the on-screen keyboard? From what I understand, whenever there's a state change, the widget will be rebuild. Hence, from below, what I did was updating the text whenever the on-screen keyboard detects tap. Then since the state is changed, I assumed it will rebuild all the widget which include the PinInput widget, and this is true since I tested the text whenever there's changes. I then did _pinPutController.text = text; to change the input of PinInput, however it is not working.
When I hardcode _pinPutController.text = '123', it works. So the problem is that it is not rebuilding. Am I understanding this correctly? How can I achieve what I wanted?
import 'package:flutter/material.dart';
import 'package:numeric_keyboard/numeric_keyboard.dart';
import 'package:pinput/pin_put/pin_put.dart';
import '../../../../constants.dart';
import '../../../../size_config.dart';
class InputForm extends StatefulWidget {
#override
_InputFormState createState() => _InputFormState();
}
class _InputFormState extends State<InputForm> {
String text = '';
#override
Widget build(BuildContext context) {
return Column(
children: [
PinInput(text: text),
NumericKeyboard(
onKeyboardTap: (value) {
setState(() {
text += value;
});
},
textColor: Colors.red,
rightButtonFn: () {
setState(() {
text = text.substring(0, text.length - 1);
});
},
rightIcon: Icon(
Icons.backspace,
color: Colors.red,
),
mainAxisAlignment: MainAxisAlignment.spaceEvenly),
],
);
}
}
class PinInput extends StatelessWidget {
const PinInput({
Key key,
this.text,
}) : super(key: key);
final String text;
#override
Widget build(BuildContext context) {
final size = getProportionateScreenHeight(60);
final TextEditingController _pinPutController = TextEditingController();
final FocusNode _pinPutFocusNode = FocusNode();
_pinPutFocusNode.unfocus();
print(text);
_pinPutController.text = text;
return PinPut(
fieldsCount: 4,
onSubmit: (String pin) => {},
focusNode: _pinPutFocusNode,
controller: _pinPutController,
preFilledWidget: Align(
alignment: Alignment.bottomCenter,
child: Divider(
color: kPrimaryColor,
thickness: 2.5,
indent: 7.5,
endIndent: 7.5,
),
),
textStyle: TextStyle(
fontSize: getProportionateScreenHeight(24),
),
eachFieldPadding: EdgeInsets.all(
getProportionateScreenHeight(10),
),
eachFieldMargin: EdgeInsets.all(
getProportionateScreenWidth(5),
),
eachFieldHeight: size,
eachFieldWidth: size,
submittedFieldDecoration: boxDecoration(),
selectedFieldDecoration: boxDecoration(),
followingFieldDecoration: boxDecoration(),
inputDecoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
counterText: '',
),
withCursor: true,
pinAnimationType: PinAnimationType.scale,
animationDuration: kAnimationDuration,
);
}
BoxDecoration boxDecoration() {
return BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(
getProportionateScreenWidth(10),
),
);
}
}
The problem is that you recreate a new TextEditingController at each rebuild of your PinInput Widget. However, if you check the PinPutState of the pinput package, it keeps a reference to the first TextEditingController you provide in its initState method:
#override
void initState() {
_controller = widget.controller ?? TextEditingController();
[...]
}
So, you have to keep the same TextEditingController all the way.
The easiest way to fix this would be to raise the TextEditingController to the State of InputForm. Instead of a String text, just use a Controller:
class InputForm extends StatefulWidget {
#override
_InputFormState createState() => _InputFormState();
}
class _InputFormState extends State<InputForm> {
TextEditingController _controller = TextEditingController(text: '');
#override
Widget build(BuildContext context) {
return Column(
children: [
PinInput(controller: _controller),
NumericKeyboard(
onKeyboardTap: (value) => _controller.text += value,
textColor: Colors.red,
rightButtonFn: () => _controller.text =
_controller.text.substring(0, _controller.text.length - 1),
rightIcon: Icon(Icons.backspace, color: Colors.red),
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
);
}
}
Note: Since you use a TextEditingController instead of a String, you can get rid of all your setState methods.
Full source code:
import 'package:flutter/material.dart';
import 'package:numeric_keyboard/numeric_keyboard.dart';
import 'package:pinput/pin_put/pin_put.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: InputForm()),
);
}
}
class InputForm extends StatefulWidget {
#override
_InputFormState createState() => _InputFormState();
}
class _InputFormState extends State<InputForm> {
TextEditingController _controller = TextEditingController(text: '');
#override
Widget build(BuildContext context) {
return Column(
children: [
PinInput(controller: _controller),
NumericKeyboard(
onKeyboardTap: (value) => _controller.text += value,
textColor: Colors.red,
rightButtonFn: () => _controller.text =
_controller.text.substring(0, _controller.text.length - 1),
rightIcon: Icon(Icons.backspace, color: Colors.red),
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
);
}
}
class PinInput extends StatelessWidget {
const PinInput({
Key key,
this.controller,
}) : super(key: key);
final TextEditingController controller;
#override
Widget build(BuildContext context) {
final size = 60.0;
final FocusNode _pinPutFocusNode = FocusNode();
_pinPutFocusNode.unfocus();
return PinPut(
fieldsCount: 4,
onSubmit: (String pin) => {},
focusNode: _pinPutFocusNode,
controller: controller,
preFilledWidget: Align(
alignment: Alignment.bottomCenter,
child: Divider(
color: Theme.of(context).primaryColor,
thickness: 2.5,
indent: 7.5,
endIndent: 7.5,
),
),
textStyle: TextStyle(
fontSize: 24,
),
eachFieldPadding: EdgeInsets.all(
10,
),
eachFieldMargin: EdgeInsets.all(
5,
),
eachFieldHeight: size,
eachFieldWidth: size,
submittedFieldDecoration: boxDecoration(),
selectedFieldDecoration: boxDecoration(),
followingFieldDecoration: boxDecoration(),
inputDecoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
counterText: '',
),
withCursor: true,
pinAnimationType: PinAnimationType.scale,
animationDuration: Duration(milliseconds: 500),
);
}
BoxDecoration boxDecoration() {
return BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(
10,
),
);
}
}
UPDATE: How to hide the Keyboard...
...while keeping the focus blinking cursor
1. disable the focus on your PinPut fields:
For this, I used a class described here:
class AlwaysDisabledFocusNode extends FocusNode {
#override
bool get hasFocus => false;
}
...as the focusNode of the PinPut:
class PinInput extends StatelessWidget {
[...]
#override
Widget build(BuildContext context) {
final size = 60.0;
final FocusNode _pinPutFocusNode = AlwaysDisabledFocusNode();
// _pinPutFocusNode.unfocus();
return PinPut(
[...]
focusNode: _pinPutFocusNode,
[...]
);
}
}
So, now, the PinPut never gets the focus. The Soft Keyboard is not shown but, hey!, we lost the blinking cursor!
No worries, we'll keep it always on programmatically.
2. Keep the blinking cursor always on
For this, though, we'll have to change the code of the pinput package.
Currently, in PinPutState, the blinking cursor is shown on the next field if withCursor is set to true and the PinPut has the focus. Instead, we will always show the blinking cursor if withCursoris set to true:
if (widget.withCursor /* && _focusNode!.hasFocus */ && index == pin.length) {
return _buildCursor();
}
Voilà! Does it work for you?
This has been mentioned on PinPut GitHub Issue Tracker [ref] about disabling the device keyboard when using a custom keyboard.
Related
Is Any Way How to pass a widget function to another page that is without any stateless/stateful? The file only includes widgets such as textfields, buttons and etc. I am trying not to cluster every fields in one page. Any helps/ideas would be appreciated!
Main.dart
class MainPage extends StatefulWidget {
const MainPage({super.key});
#override
State<Main Page> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
// bool for toggling password
bool isSecuredPasswordField = true;
#override
Widget build(BuildContext context) {
return Container();
}
// widget function that I need to pass on widget_fields.dart
Widget togglePassword() {
return IconButton(
onPressed: () {
setState(() {
isSecuredPasswordField = !isSecuredPasswordField;
});
},
icon: isSecuredPasswordField
? const Icon(Icons.visibility)
: const Icon(Icons.visibility_off),
);
}
}
widget_fields.dart
Widget userPasswordField(_passwordUserCtrlr) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: TextFormField(
obscureText: true,
controller: _passwordUserCtrlr,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
isDense: true,
suffixIcon: togglePassword(), //<-- I wanna call that function here
prefixIcon: const Icon(Icons.lock),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xFFCECECE)),
borderRadius: BorderRadius.circular(12),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFCECECE)),
),
hintText: 'Password',
hintStyle: const TextStyle(
fontFamily: 'Poppins',
fontSize: 14,
),
fillColor: const Color(0xFFFEFEFE),
filled: true,
),
validator: (value) {
if (value!.isEmpty) {
return "Please enter your password.";
} else if (value.length < 8) {
return "Password should be min. 8 characters.";
} else {
return null;
}
},
),
);
}
You can pass functions like any other variable. I made a full working example that's different than yours to show a more minimal example but you can apply the same logic for your code
main.dart
import 'package:flutter/material.dart';
import 'column.dart';
void main() {
runApp(const MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
Widget returnSomeText() {
return const Text("test");
}
#override
Widget build(BuildContext context) {
return Scaffold(body: createColumn(returnSomeText));
}
}
column.dart
import 'package:flutter/material.dart';
Widget createColumn(Function widgetFunction) {
return Column(
children: [widgetFunction(), widgetFunction()],
);
}
As you can see the togglePassword from your code corresponds to returnSomeText in mine. and userPasswordField is like createColumn. But it must be said that it's not recommended to use helper functions like createColumn here but to turn it into a StatelessWidget, like this for example:
import 'package:flutter/material.dart';
class CreateColumn extends StatelessWidget {
final Function widgetFunction;
const CreateColumn({Key? key, required this.widgetFunction}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: [widgetFunction(), widgetFunction()],
);
}
}
And then in main.dart:
return Scaffold(body: CreateColumn(widgetFunction: returnSomeText));
See also this YouTube video: Widgets vs helper methods
This is Example that how you call Widget in another class:
class MainApge extends StatefulWidget {
const MainApge({Key? key}) : super(key: key);
#override
State<MainApge> createState() => _MainApgeState();
}
class _MainApgeState extends State<MainApge> {
#override
Widget build(BuildContext context) {
return Column(
children: [
ContainerTextFields.customsTextField(
"User Name",
'enter name',
userNameController,
),
],
);
}
}
This is Custom Widget Class:
class ContainerTextFields {
static Widget customsTextField(
String label, String cusHintText, TextEditingController _controller) {
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: EdgeInsets.only(
left: SizeConfig.screenHeight! * 0.05,
top: SizeConfig.screenHeight! * 0.03),
child: Text(
label,
style: AppStyle.kUnSyncedDialogeText.copyWith(
color: AppColors.kTextFieldLabelColorGrey,
fontWeight: FontWeight.bold),
)),
Padding(
padding: EdgeInsets.only(
top: SizeConfig.screenHeight! * 0.02,
left: SizeConfig.screenHeight! * 0.042,
right: SizeConfig.screenWidth! * 0.042),
child: SingleChildScrollView(
child: Container(
height: SizeConfig.screenHeight! * 0.065,
child: TextFormField(
controller: _controller,
decoration: InputDecoration(
hintText: cusHintText,
hintStyle: TextStyle(
color: AppColors.kLoginPopUpColor,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
),
)
]);
}
}
You can pass the widget as parameter to child widget:
class MyTextField extends StatelessWidget {
const MyTextField({Key? key,
this.togglePassword,
this.passwordUserCtrlr
})
: super(key: key);
final Widget? togglePassword;
final TextEditingController? passwordUserCtrlr;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: TextFormField(
obscureText: true,
controller: passwordUserCtrlr,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
isDense: true,
suffixIcon: togglePassword, //<-- I wanna call that function here
prefixIcon: const Icon(Icons.lock),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Color(0xFFCECECE)),
borderRadius: BorderRadius.circular(12),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFFCECECE)),
),
hintText: 'Password',
hintStyle: const TextStyle(
fontFamily: 'Poppins',
fontSize: 14,
),
fillColor: const Color(0xFFFEFEFE),
filled: true,
),
validator: (value) {
if (value!.isEmpty) {
return "Please enter your password.";
} else if (value.length < 8) {
return "Password should be min. 8 characters.";
} else {
return null;
}
},
),
);
}
}
And can easily call from main widget:
class MainPage extends StatefulWidget {
const MainPage({super.key});
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
// bool for toggling password
bool isSecuredPasswordField = true;
TextEditingController? passwordUserCtrlr = TextEditingController();
#override
Widget build(BuildContext context) {
return MyTextField(
togglePassword: togglePassword(),
passwordUserCtrlr: passwordUserCtrlr,
);
}
// widget function that I need to pass on widget_fields.dart
Widget togglePassword() {
return IconButton(
onPressed: () {
setState(() {
isSecuredPasswordField = !isSecuredPasswordField;
});
},
icon: isSecuredPasswordField
? const Icon(Icons.visibility)
: const Icon(Icons.visibility_off),
);
}
}
You can create class like GlobalWidget for example, like this:
class GlobalWidget {
// widget function that I need to pass on widget_fields.dart
Widget togglePassword(Function()? onPressed, bool value) {
return IconButton(
onPressed: onPressed,
icon: value
? const Icon(Icons.visibility)
: const Icon(Icons.visibility_off),
);
}
}
And You can call the Widget like that :
GlobalWidget().togglePassword(() => setState(() {
isSecuredPasswordField = !isSecuredPasswordField;
}), isSecuredPasswordField)
What you are trying to do is impossible in the Flutter framework. You cannot call methods belonging to other widgets
Also, it is discouraged to use function to return widgets as this impacts the framework's ability to optimize the build process.
One possible solution is to package your complete password entry in a set of custom (statefull) widgets. You can collect those into a single source file if you like. Be sure to create a class for every widget.
I want to enter Arabic numbers in my application. How to insert an Arabic number keyboard in the flutter app?
I have tried a lot but couldn't find the solution.
I had to change the source code of the virtual_keyboard_multi_language: ^1.0.3 package to get the desired output. The package used English numbers on an Arabic keyboard so I just change the keys from English to Arabic.
Step 1
Install virtual_keyboard_multi_language: ^1.0.3 package
Step 2
copy and paste this demo code in main.dart
import 'package:flutter/material.dart';
import 'package:virtual_keyboard_multi_language/virtual_keyboard_multi_language.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TextEditingController textEditingController = TextEditingController();
bool showKeyboard = false;
late FocusNode focusNode;
#override
void initState() {
super.initState();
focusNode = FocusNode();
// listen to focus changes
focusNode.addListener(() {
if (focusNode.hasFocus == false && showKeyboard == false) {
setState(() {
showKeyboard = false;
});
}
});
}
void setFocus() {
FocusScope.of(context).requestFocus(focusNode);
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
if (focusNode.hasFocus == false) {
setState(() {
showKeyboard = false;
});
}
},
child: Scaffold(
body: Stack(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: TextField(
focusNode: focusNode,
keyboardType: TextInputType.none,
controller: textEditingController,
textDirection: TextDirection.rtl,
onTap: () {
setState(() {
showKeyboard = true;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
borderRadius: BorderRadius.circular(10),
),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
borderRadius: BorderRadius.circular(10),
),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.black),
borderRadius: BorderRadius.circular(10),
)),
),
),
],
),
Positioned(
bottom: 0,
child: showKeyboard
? Container(
color: Colors.black,
child: VirtualKeyboard(
fontSize: 20,
textColor: Colors.white,
textController: textEditingController,
type: VirtualKeyboardType.Alphanumeric,
defaultLayouts: const [
VirtualKeyboardDefaultLayouts.Arabic
],
),
)
: Container(),
)
],
)),
);
}
}
Step 3
go to "flutter_windows_3.3.4-stable\flutter.pub-cache\hosted\pub.dartlang.org\virtual_keyboard_multi_language-1.0.3\lib\src\layout_keys.dart"
and change in line 111
from
const [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'0',
],
to
const ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'],
Step 4
Restart the program to see the Arabic keyboard
Output
Hope this helps. Happy Coding :)
I have two screens with different size of text fields. I am trying to make a hero animation for them. I want the end text field to auto focus, but the keyboard get dismissed at the second screen.
I tried to use flightShuttleBuilder to check if the animation is completed and request focus. But it is not working.
Here is the code for the second screen
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Search extends ConsumerStatefulWidget {
#override
ConsumerState createState() => _SearchState();
}
class _SearchState extends ConsumerState<Search> {
FocusNode focusNode = FocusNode();
#override
void initState() {
// TODO: implement initState
super.initState();
// focusNode = FocusNode();
// focusNode?.requestFocus()
}
#override
void dispose() {
// TODO: implement dispose
focusNode.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) => () => focusNode.requestFocus());
Size size = MediaQuery.of(context).size;
focusNode.requestFocus();
return Scaffold(
appBar: AppBar(
title: Container(
child: Hero(
tag:'searchBar',
flightShuttleBuilder: ((flightContext, animation, flightDirection, fromHeroContext, toHeroContext){
animation.addStatusListener((status) {
if (status == AnimationStatus.completed) {
focusNode.requestFocus();
}
});
return toHeroContext.widget;
}),
child: Material(
type: MaterialType.transparency,
child: SizedBox(
height:size.height * 0.05,
child: TextField(
focusNode: focusNode,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search, size: 25.0,),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
hintStyle: TextStyle(color: Colors.grey[800]),
hintText: 'Search a word',
fillColor: Colors.white,
// isDense: true,
contentPadding: EdgeInsets.all(0.0),
),
),
),
),
),
),
),
body: Container(),
);
}
}
My first advice is avoid doing calculations or calling methods in the build method, this will cause to be called each time the widget tree needs to refresh (unless you use Flutter Hooks which holds the state of what is currently doing, but thats a different story)
class Search extends ConsumerStatefulWidget {
#override
ConsumerState createState() => _SearchState();
}
class _SearchState extends ConsumerState<Search> {
FocusNode focusNode = FocusNode();
#override
void initState() {
// TODO: implement initState
super.initState();
// focusNode = FocusNode();
// focusNode?.requestFocus()
}
#override
void dispose() {
// TODO: implement dispose
focusNode.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
/// no Widget WidgetsBinding.instance.addPostFrameCallback nor requestFocus call here
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Container(
child: Hero(
tag: 'searchBar',
flightShuttleBuilder: ((flightContext, animation, flightDirection,
fromHeroContext, toHeroContext) {
/// Don't try to add a Listener here, use a StatefulWidget that uses that logic in its initState
return _FocustWidget(
animation: animation,
child: toHeroContext.widget,
focusNode: focusNode,
);
}),
child: Material(
type: MaterialType.transparency,
child: SizedBox(
height: size.height * 0.05,
child: TextField(
focusNode: focusNode,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.search,
size: 25.0,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
hintStyle: TextStyle(color: Colors.grey[800]),
hintText: 'Search a word',
fillColor: Colors.white,
// isDense: true,
contentPadding: EdgeInsets.all(0.0),
),
),
),
),
),
),
),
body: Container(),
);
}
}
class _FocustWidget extends StatefulWidget {
final Widget child;
final Animation<double> animation;
final FocusNode focusNode;
const _FocustWidget({
Key? key,
required this.focusNode,
required this.animation,
required this.child,
}) : super(key: key);
#override
State<_FocustWidget> createState() => __FocustWidgetState();
}
class __FocustWidgetState extends State<_FocustWidget> {
#override
void initState() {
super.initState();
widget.animation.addStatusListener(_status); ///Check for the animation state
}
void _status(AnimationStatus status) {
if (status == AnimationStatus.completed) {
Future.microtask(() => mounted ? widget.focusNode.requestFocus() : null);
}
}
#override
void dispose() {
widget.animation.removeStatusListener(_status); /// dispose the listener
super.dispose();
}
#override
Widget build(BuildContext context) => widget.child;
}
Now I talked about hooks because I see you using Consumer so I believe you use riverpod (and therefore maybe you are familiar with hooks if you saw hooks_riverpod package). If you're still grasping the concept of riverpod without hook then this is it, else you could try using hooks to reduce the statefulWidget:
class Search extends HookConsumerWidget {
#override
Widget build(BuildContext context, WidgetRef ref) {
final focusNode = useFocusNode(); /// created once with hook
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Container(
child: Hero(
tag: 'searchBar',
flightShuttleBuilder: ((flightContext, animation, flightDirection,
fromHeroContext, toHeroContext) {
return HookBuilder(
builder: (context) {
final mounted = useIsMounted();
useEffect(() {
if (animation.status == AnimationStatus.completed) {
Future.microtask(
() => mounted() ? focusNode.requestFocus() : null,
);
return null;
}
void _status(AnimationStatus status) {
if (status == AnimationStatus.completed) {
Future.microtask(
() => mounted() ? focusNode.requestFocus() : null,
);
}
}
animation.addStatusListener(_status);
return () => animation.removeStatusListener(_status);
}, const []);
return toHeroContext.widget;
},
);
}),
child: Material(
type: MaterialType.transparency,
child: SizedBox(
height: size.height * 0.05,
child: TextField(
focusNode: focusNode,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.search,
size: 25.0,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
hintStyle: TextStyle(color: Colors.grey[800]),
hintText: 'Search a word',
fillColor: Colors.white,
// isDense: true,
contentPadding: EdgeInsets.all(0.0),
),
),
),
),
),
),
),
body: Container(),
);
}
}
I wanted to implement an age verification process but to get the age I need Textfields where the birthdate can be typed in. This is the code for the Textfield I have right now:
class TextFieldAgeInput extends StatelessWidget {
TextFieldAgeInput({
Key? key,
required this.textController,
required this.leftPadding,
required this.hintText,
}) : super(key: key);
TextEditingController textController;
double leftPadding;
String hintText;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(
left: leftPadding,
top: 5,
),
child: Container(
height: 40,
width: 30,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(10),
border: Border.all(
width: 1,
color: primaryColor,
),
),
child: Padding(
padding: const EdgeInsets.only(
bottom: 5,
left: 1,
),
child: TextField(
keyboardType: TextInputType.number,
style: GoogleFonts.poppins(
textStyle: const TextStyle(
color: mainTextColor,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
textAlign: TextAlign.center,
controller: textController,
decoration: InputDecoration(
hintText: hintText,
hintStyle: GoogleFonts.poppins(
textStyle: const TextStyle(
color: primaryColor,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
border: InputBorder.none,
),
onChanged: (textController) {
TextInputAction.next;
},
),
),
),
);
}
}
In the code of the screen I call the widget several times with the padding and so on. Now how can I make the textfield switch to the next one when 1 number was given (Keyboard = numberkeyboard)?
thanks for the help in advance
There are fundamental mistakes in your code like here:
onChanged: (textController) {
TextInputAction.next;
},
The onChanged property is a call back that gives you the updated text. It doesn't give you textController. Inside the body, you're using a definition that does nothing TextInputAction.next;. This should be assigned to the TextField as keyboardType: TextInputType.number.
Anyway, below is a fully runnable example that I wrote a while back and which tackle the same problem you're trying to solve. The example was for verification code but it applies to birth year as well (since both are four fields).
In the example, you'll see that each field has its own TextEditingController and FocusNode. We use the controller for setting/retrieving the value while the focus node is used to move the focus from one field to another.
The example also uses a workaround to detect when the user clicks backspace (see note at the bottom) hence you'll see zero width space character added to the controller but removed when we added to code (would be age in your example). There are notes about this within the code.
You can see the code running on DartPad here: Multiple Text Fields Example or you can copy it to your editor and run it:
// ignore_for_file: avoid_function_literals_in_foreach_calls, avoid_print
import 'package:flutter/material.dart';
void main() => runApp(MultipleTextFieldsExampleApp());
class MultipleTextFieldsExampleApp extends StatelessWidget {
const MultipleTextFieldsExampleApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: const Center(child: CodeField()),
);
}
}
/// zero-width space character
///
/// this character can be added to a string to detect backspace.
/// The value, from its name, has a zero-width so it's not rendered
/// in the screen but it'll be present in the String.
///
/// The main reason this value is used because in Flutter mobile,
/// backspace is not detected when there's nothing to delete.
const zwsp = '\u200b';
// the selection is at offset 1 so any character is inserted after it.
const zwspEditingValue = TextEditingValue(text: zwsp, selection: TextSelection(baseOffset: 1, extentOffset: 1));
class CodeField extends StatefulWidget {
const CodeField({Key? key}) : super(key: key);
#override
_CodeFieldState createState() => _CodeFieldState();
}
class _CodeFieldState extends State<CodeField> {
List<String> code = ['', '', '', ''];
late List<TextEditingController> controllers;
late List<FocusNode> focusNodes;
#override
void initState() {
super.initState();
focusNodes = List.generate(4, (index) => FocusNode());
controllers = List.generate(4, (index) {
final ctrl = TextEditingController();
ctrl.value = zwspEditingValue;
return ctrl;
});
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
// give the focus to the first node.
focusNodes[0].requestFocus();
});
}
void printValues() {
print(code);
}
#override
void dispose() {
super.dispose();
focusNodes.forEach((focusNode) {
focusNode.dispose();
});
controllers.forEach((controller) {
controller.dispose();
});
}
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
4,
(index) {
return Container(
width: 20,
height: 20,
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: TextField(
controller: controllers[index],
focusNode: focusNodes[index],
maxLength: 2,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
counterText: "",
),
onChanged: (value) {
if (value.length > 1) {
// this is a new character event
if (index + 1 == focusNodes.length) {
// do something after the last character was inserted
FocusScope.of(context).unfocus();
} else {
// move to the next field
focusNodes[index + 1].requestFocus();
}
} else {
// this is backspace event
// reset the controller
controllers[index].value = zwspEditingValue;
if (index == 0) {
// do something if backspace was pressed at the first field
} else {
// go back to previous field
controllers[index - 1].value = zwspEditingValue;
focusNodes[index - 1].requestFocus();
}
}
// make sure to remove the zwsp character
code[index] = value.replaceAll(zwsp, '');
print('current code = $code');
},
),
);
},
),
);
}
}
In Flutter, backspace does not trigger onChanged when the TextField is empty, so that's why the workaround exists.
As you can see, the height is different.
The picture on the left shows the app running when the keyboard did not pop up. And the picture on the right shows the app running when keyboard pops up and clicks "Flutter Hot Reload"(Android Studio).
I want the textfield to be like the picture on the right without keyboard pop-up.
How can I fix this?
Appbar
class CustomAppbar extends StatelessWidget with PreferredSizeWidget{
#override
final Size preferredSize;
#override
static double height = AppBar().preferredSize.height;
CustomAppbar() : preferredSize = Size.fromHeight(height);
#override
Widget build(BuildContext context) {
#override
final double statusbarHeight = MediaQuery.of(context).padding.top;
return Container(
child: Stack(
children: <Widget>[
AppBar(
backgroundColor: Colors.white,
elevation: 0,
iconTheme: IconThemeData(color: Colors.black,),
),
Container(
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(10))
),
margin: EdgeInsets.only(left: 60, top: statusbarHeight + 5, bottom: 5, right: 5),
child: InputBox(),
)
],
),
);
}
}
InputBox
class InputBox extends StatefulWidget {
#override
_InputBoxState createState() => _InputBoxState();
}
class _InputBoxState extends State<InputBox> {
TextEditingController _SearchController = TextEditingController();
FocusNode _focusNode = FocusNode();
String _SearchText = "";
_InputBoxState(){
_SearchController.addListener(() {
setState((){
_SearchText = _SearchController.text;
});
});
}
#override
Widget build(BuildContext context) {
return TextField(
focusNode: _focusNode,
style: TextStyle(fontSize: 19),
controller: _SearchController,
decoration: InputDecoration(
hintText: "Search",
border: InputBorder.none,
prefixIcon: Icon(Icons.search, color: Colors.white,),
suffixIcon: _focusNode.hasFocus ? IconButton(
icon: Icon(Icons.cancel, color: Colors.white,),
onPressed: (){
setState((){
_SearchController.clear();
_SearchText = "";
_focusNode.unfocus();
});
},
) : Container()
)
);
}
}
style:TextStyle(height: 20), //custome height
decoration: InputDecoration(
isDense: true) // remove padding inside textfield
you can use ContentPadding if you want give padding inside textfield