Can we refactor TextField/TextFormField in Flutter without rebuilding the Widget?
I tried to refactor the TextField Widget for a form that I have created to collect some data. But, when I dismiss my keyboard, the data is losing because the widget is rebuilding. Is there any way to fix it? Pls, Let me know...
See the code below of the Refactored TextField
import 'package:flutter/material.dart';
class ContentInputWidget extends StatelessWidget {
const ContentInputWidget({
Key? key,
required this.text,
required this.controller,
this.keyboardType = TextInputType.text,
}) : super(key: key);
final String text;
final TextInputType keyboardType;
final TextEditingController controller;
#override
Widget build(BuildContext context) {
print('Content Input Widget Rebuild');
return TextField(
decoration: InputDecoration(
labelText: text,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
controller: controller,
keyboardType: keyboardType,
maxLines: null,
);
}
}
I've used Provider and Consumer to get the data from the text field. And I got it by using a Providers Model Class
See below
class ContentUpdater extends ChangeNotifier {
String description = 'Description comes here';
String name = 'Name';
String prayerRequest = 'Request Comes here';
String postDate = '01-01-2022';
void updatePoster(
String nameText,
String descriptionText,
String prayerReqText,
String postDtText,
) {
name = nameText;
description = descriptionText;
prayerRequest = prayerReqText;
postDate = postDtText;
notifyListeners();
}
}
Called a Function to Update Content using Provider
() { Provider.of<ContentUpdater>(context, listen: false)
.updatePoster(
nameController.text.toString(),
descriptionController.text.toString(),
requestController.text.toString(),
dateController.text.toString(),
);
}
This all works well. But the problem comes if we dismiss the keyboard by clicking the back button, the content disappears from the TextField ...
Is there any way to do without using a StateFulWidget
You can set up your TextFieldController using flutter_hooks (useTextEditingController). This will make it so the state of the TextEditingController isn't lost on rebuilds.
TextEditingController controller = useTextEditingController();
I had a similar problem a long time ago. I don't remember exactly how I made it work, but you could try adding a onChanged function to your TextField and save the data before the re-build clears the text.
final String myText;
void _onChanged() {
if (controller.text != null && controller.text != "") {
myText = controller.text;
}
}
#override
Widget build(BuildContext context) {
print('Content Input Widget Rebuild');
return TextField(
onChanged: _onChanged,
decoration: InputDecoration(
labelText: text,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
controller: controller,
keyboardType: keyboardType,
maxLines: null,
);
}
The problem is probably there because the controller is inside the stateless widget. When the state is changed, controller dies and gets rebuilt. Try wrapping widget inside a stateful widget and maybe it'll solve your issue.
import 'package:flutter/material.dart';
class ContentInputWidget extends StatefulWidget {
const ContentInputWidget({
Key? key,
required this.text,
required this.controller,
this.keyboardType = TextInputType.text,
}) : super(key: key);
final String text;
final TextInputType keyboardType;
final TextEditingController controller;
#override
State<ContentInputWidget> createState() => _ContentInputWidgetState();
}
class _ContentInputWidgetState extends State<ContentInputWidget> {
#override
Widget build(BuildContext context) {
print('Content Input Widget Rebuild');
return TextField(
decoration: InputDecoration(
labelText: widget.text,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
),
controller: widget.controller,
keyboardType: widget.keyboardType,
maxLines: null,
);
}
}
Related
enter image description hereI have a probelm with the PageController. As soon as I enter a text and then change the page and then come back again, it deletes all the information I entered before. How can I fix this?
Here its my Code about de override:
class AAddTitleComponent extends StatefulWidget {
#override
State<AAddTitleComponent> createState() => _AAddTitleComponentState();
}
class _AAddTitleComponentState extends State<AAddTitleComponent>
with WidgetsBindingObserver {
TextEditingController vehicleTitleTextEditingController =
TextEditingController();
TextEditingController vehiclePSDescriptionTextEditingController =
TextEditingController();
String downloadUrlImage = '';
String vehicleID = DateTime.now().millisecondsSinceEpoch.toString();
File? image;
Future pickImage(ImageSource source) async {
try {
final image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final imageTemp = File(image.path);
setState(() => this.image = imageTemp);
} on PlatformException catch (e) {
print('Kein Bild ausgewählt $e');
}
sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString(
'vehicleTitleInfo', vehicleTitleTextEditingController.text.toString());
await sharedPreferences.setString('image', downloadUrlImage);
}
#override
void initState() {
vehicleTitleTextEditingController = TextEditingController();
super.initState();
}
and here its the content:
children: [
SizedBox(height: MediaQuery.of(context).viewPadding.top),
SizedBox(height: 64),
Text("Fahrzeug Titel",
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 30)),
SizedBox(height: 16),
TextField(
autocorrect: true,
autofocus: true,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.done,
controller: vehicleTitleTextEditingController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
borderSide: BorderSide(
color: Colors.black,
width: 0,
),
),
fillColor: Colors.white,
filled: true,
hintText: 'Fahrzeug Titel eingeben',
labelText: 'Fahrzeug Titel',
labelStyle: TextStyle(color: Colors.black),
// alignLabelWithHint: false,
),
)
as soon as I change the pages it deletes everything for me.
as soon as I change the pages it deletes everything for me.
I am giving this solution based on the assumption that the page controller is used as a bottom navigation system or tab bar navigation system:
class MyWidget extends StatefulWidget {
const MyWidget({Key key});
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
.....
);
}
#override
bool get wantKeepAlive => true;
}
I composed a custom text field that check the validator when it lost focus, with some UI such as error text and green checked icon. They are working fine until I need to perform some auto-filling according to other TextField's data.
When user filled up the postal code, the API will be called from ChangeNotifierProvider view model and update the state according
user.prefectureName = data.prefectureName;
user.city = data.city;
user.address = data.address;
notifyListeners();
In the HookConsumerWidget page, I passed the state into the custom text field like this
OCTextField(
text: user.prefectureName,
labelText: l10n.accountProfileEditPrefectureName,
errorText: "都道府県は必須項目です",
onChanged: (value) => user.prefectureName = value,
validator: (value) => value.isNotEmpty),
OCTextField(
text: user.city,
labelText: l10n.accountProfileEditCity,
errorText: "市区町村は必須項目です",
onChanged: (value) => user.city = value,
validator: (value) => value.isNotEmpty),
OCTextField(
text: user.address,
labelText: l10n.accountProfileEditAddress,
errorText: "丁目・番地は必須項目です",
onChanged: (value) => user.address = value,
validator: (value) => value.isNotEmpty),
However, when the state change (user.prefectureName, user.city and user.address), my custom text field won't be able to reflect the changes accordingly.
Here is part of my custom text field code
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import '../util/ext/string_ext.dart';
typedef Validator = bool Function(String value);
class OCTextField extends HookWidget {
const OCTextField(
{Key? key,
this.text = "",
this.labelText,
this.hintText,
this.errorText,
this.maxLines = 1,
this.maxLength,
this.sanitise = true,
this.onChanged,
this.validator})
: super(key: key);
final String text;
final String? labelText;
final String? hintText;
final String? errorText;
final int? maxLines;
final int? maxLength;
final bool sanitise;
final ValueChanged<String>? onChanged;
final Validator? validator;
#override
Widget build(BuildContext context) {
final _showError = useState(false);
final _controller = useTextEditingController(text: text);
final _checkIcon;
final unchecked =
const Icon(Icons.check_circle_outline, color: Colors.black26);
final checked = const Icon(Icons.check_circle, color: Colors.green);
if (validator != null) {
_checkIcon = useState(validator!(_controller.text) ? checked : unchecked);
} else {
_checkIcon = useState(checked);
}
return Focus(
child: TextField(
controller: _controller,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(1.0),
),
suffixIcon: _checkIcon.value,
labelText: labelText,
hintText: hintText,
errorText: _showError.value ? errorText : null,
),
maxLines: maxLines,
maxLength: maxLength,
onChanged: onChanged),
onFocusChange: (isFocused) {
if (isFocused) {
_showError.value = false;
_checkIcon.value = unchecked;
} else {
if (sanitise) {
_controller.text = _controller.text.sanitise();
onChanged!(_controller.text.sanitise());
}
if (validator != null) {
_showError.value = !validator!(_controller.text);
}
_checkIcon.value = _showError.value ? unchecked : checked;
}
});
}
}
I actually read the documentation of useTextEditingController(text: text) which it does not react to the text changes. I tried to replace useTextEditingController to TextEditingController and it somehow works, with some strange behaviour - Even I erased the reflected pre-filled text and move the another field, the text will come back again; The cursor is acting weird, when I click on the field, it starts from the beginning of the pre-fill text.
It works perfectly without strange issue when I inherited TextField class and initialise the TextControllerEditor directly into TextField instance.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class OutlinedTextField extends TextField {
OutlinedTextField(
{String? labelText,
String? text,
String? errorText,
String? hintText,
TextInputType keyboardType = TextInputType.text,
int maxLines = 1,
Icon? icon,
List<TextInputFormatter>? inputFormatters,
ValueChanged<String>? onChanged,
isDense = false})
: super(
controller: text == null ? null : TextEditingController(text: text),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(1.0),
),
labelText: labelText,
hintText: hintText,
errorText: errorText,
prefixIcon: icon,
isDense: isDense),
keyboardType: keyboardType,
maxLines: maxLines,
inputFormatters: inputFormatters,
onChanged: onChanged,
);
}
With this approach, I am not able to obtain the controller. The reason I am refactor the Custom Text Field with composition instead of inheritance is to access the controller.text for validation UI. Am I doing some serious mistake or misunderstanding the concept here? I am not able to figure out this strange behaviour.
you have to add reusable controller in your custom textfield
Note: You have to always create a seperate controller for each textfield
class CustomTextField extends StatelessWidget {
// created custom controller
TextEditingController controller;
String text;
CustomTextField({
required this.controller,
required this.text
});
#override
Widget build(BuildContext context) {
return TextField();
}
}
then create a textEditingController for each text Filed and initilize it in oninit function.
late TextEditingController text1 ;
late TextEditingController text2 ;
use the controllers in your custom text fields
CustomTextField(controller: text1 ,text: "text1",),
CustomTextField(controller: text2 ,text: "text2",)
I have a AppTextField in flutter app as follow:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
class AppTextField extends StatefulWidget {
final int maxLines;
final String? title;
final TextInputType? keyboardType;
final bool autoFocus;
final TextInputAction inputAction;
final bool isSuffixIcon;
AppTextField(
{this.title,
this.maxLines: 1,
this.keyboardType,
this.autoFocus: false,
this.inputAction: TextInputAction.next,
this.isSuffixIcon: false});
#override
State<StatefulWidget> createState() => AppTextFieldSate();
}
class AppTextFieldSate extends State<AppTextField> {
String? text = '';
bool isRTL(String text) {
return intl.Bidi.detectRtlDirectionality(text);
}
#override
Widget build(BuildContext context) => Container(
child: TextField(
textDirection: isRTL(text!) ? TextDirection.rtl : TextDirection.ltr,
textInputAction: widget.inputAction,
keyboardType: widget.keyboardType,
autofocus: widget.autoFocus,
style: Theme.of(context).textTheme.bodyText1,
maxLines: widget.maxLines,
decoration: InputDecoration(
labelText: widget.title,
suffixIcon: widget.isSuffixIcon
? Icon(Icons.check_circle, color: Theme.of(context).hintColor)
: Container(),
),
onChanged: (value) {
setState(() {
text = value;
});
}));
}
When I use maxLines in AppTextField, there is a problem!
AppTextField(maxLines: 5, keyboardType: TextInputType.multiline)
Only one character is entered in a line as follow picture:
My question is:
Why occur this problem and I how to resolve it?
I resolved it :)
I must use null instead of Container in suffixIcon widget.
Container widget make to problem.
suffixIcon: widget.isSuffixIcon
? Icon(Icons.check_circle, color: Theme.of(context).hintColor)
: null,
In the below code widget.hintText is giving the error, I am trying to make the datepicker as the seperate component and dynamically pass the hinttext value whenever calling it from the other file.
import 'package:date_field/date_field.dart';
import 'package:flutter/material.dart';
class DatePicker extends StatefulWidget {
final String hintText;
DatePicker({
this.hintText,
Key key,
}): super(key: key);
#override
_DatePickerState createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
#override
Widget build(BuildContext context) {
return DateTimeFormField(
decoration: const InputDecoration(
hintText: widget.hintText,
hintStyle: TextStyle(color: Colors.black54,fontSize: 16),
errorStyle: TextStyle(color: Colors.redAccent),
suffixIcon: Icon(Icons.event_note),
),
mode: DateTimeFieldPickerMode.date,
autovalidateMode: AutovalidateMode.always,
// validator: (e) => (e?.day ?? 0) == 1 ? 'Please not the first day' : null,
onDateSelected: (DateTime value) {
},
);
}
}
The error comes from the fact of using a variable widget.hint inside of const object InputDecoration
I can't find anywhere in the date_field code where it forces you to use a constant decoration
So you might just remove the const keyword in front of InputDecoration
See this answer for details about the difference between const and final
Try removing the const for the InputDecoration()
You can try removing the final keyword from the string
I am getting some strange issue where one of TextField always gets clears if you tap on it.
class MyEditText extends StatefulWidget {
static String tag = "MyEditText";
#override
MyEditTextState createState() => MyEditTextState();
}
class MyEditTextState extends State<MyEditText> {
String results = "";
final TextEditingController controller = new TextEditingController();
final TextEditingController controller1 = new TextEditingController();
#override
Widget build(BuildContext context) {
final email = TextField(
decoration: InputDecoration(
hintText: 'Enter Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0)),
);
final password = TextField(
obscureText: true,
decoration: InputDecoration(
hintText: 'Enter Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
),
);
return new Scaffold(
appBar: new AppBar(
automaticallyImplyLeading: false,
title: new Text("EditText Sample"),
backgroundColor: Colors.yellow,
),
body: new Container(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[email, password],
),
),
);
}
}
I am using statful widget for it and all classes from where this screen launch also statful.
Note: If I comment out all TextEditingController and its usage, everything works fine, SO I m not getting what is wrong with TextEditingController
Thanks for the updated code.
The reason your TextEditingController get cleared is because you declare the variables inside of State<MyEditText>. When the State gets re-initialized - those variables do, too.
I can see 2 ways to solve this:
#1 - Move controllers out of the State to the parent class, passing them as arguments
Controllers are declared and maintained outside of MyEditText widget - in the parent class.
class MyEditText extends StatefulWidget {
MyEditText({ Key key, this.emailController, this.passwordController }): super(key: key);
final TextEditingController emailController;
final TextEditingController passwordController;
static String tag = "MyEditText";
#override
MyEditTextState createState() => MyEditTextState();
}
class MyEditTextState extends State<MyEditText> {
String results = "";
#override
Widget build(BuildContext context) {
// ...
TextField(
controller: widget.emailController,
// ...,
),
TextField(
controller: widget.passwordController,
// ...,
),
// ...
}
}
Then you declare controllers in your parent class and pass them as arguments to MyEditText:
final emailController = TextEditingController();
final passwordController = TextEditingController();
// ...
MyEditText(
emailController: emailController,
passwordController: passwordController,
)
#2 - Reuse controllers from the old state on didUpdateWidget call
Controllers can be declared outside of MyEditText class, but if they were not - widget creates and maintains TextEditingController on its own.
class MyEditText extends StatefulWidget {
MyEditText({ Key key, this.emailController, this.passwordController }): super(key: key);
final TextEditingController emailController;
final TextEditingController passwordController;
static String tag = "MyEditText";
#override
MyEditTextState createState() => MyEditTextState();
}
class MyEditTextState extends State<MyEditText> {
TextEditingController _emailController;
TextEditingController _passwordController;
#override
void initState() {
super.initState();
if (widget.emailController == null)
_emailController = TextEditingController();
if (widget.passwordController == null)
_passwordController = TextEditingController();
}
#override
void didUpdateWidget(MyEditText oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.emailController == null && oldWidget.emailController != null)
_emailController = TextEditingController.fromValue(oldWidget.emailController.value);
else if (widget.emailController != null && oldWidget.emailController == null)
_emailController = null;
if (widget.passwordController == null && oldWidget.passwordController != null)
_passwordController = TextEditingController.fromValue(oldWidget.passwordController.value);
else if (widget.passwordController != null && oldWidget.passwordController == null)
_passwordController = null;
}
#override
Widget build(BuildContext context) {
// ...
TextField(
controller: _emailController ?? widget.emailController,
// ...,
),
TextField(
controller: _passwordController ?? widget.passwordController,
// ...,
),
// ...
}
// ...
}
Both methods are similar except that the second one regulates State<MyEditText> variables on its own.
I will leave it to you to decide which one is more suitable in your case.
Let me know if this helped.
TextEditingController controller = TextEditingController();
TextEditingController controller1 = TextEditingController();
final email = TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
prefixIcon: Icon(Icons.person_outline, color: Colors.grey),
hintText: 'Enter Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0)),
);
final password = TextField(
controller1: passwordController,
obscureText: true,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
hintText: 'Enter Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
),
);
clearName() {
controller.text = '';
controller1.text = '';
}
//call the clearName function wherever needed
Can you try this way
TextFormField(
cursorColor: Colors.white,
autofocus: false,
keyboardType:
TextInputType.emailAddress,
controller: _textEditingControllerEmail,
),
TextFormField(
autofocus: false,
controller:_textEditingControllerPassword,
cursorColor: Colors.white,
obscureText: true,
),