State of the dialog not updating on dropdown change - flutter

So I have this function to show a reusable dialog that have a list of widget. The main problem lies in the dropdown and the text field. to begin with my dropdown value is A and I wanted the text field to only show when the dropdown value is B.
I tried some code already but when I choose the value B the text field won't show up, then if I close the dialog and try to open it again next time, that will show the text field that I want, but the value in the drop down is A not value B.
How can I achieve something like what I wanted ?
Here's my code :
List<String> itemList = ["notMyExpertise", "Alasan lainnya"];
String selectedReason = '';
void rejectDialog(
{required dynamic ticketData,
required String ticketId,
required VoidCallback onDeclineConfirmed}) {
showDialog(
context: context,
builder: (context) {
return ReusableConfirmationDialog(
titleText: 'hello'.tr(),
contentText: 'hello bro let me try to help you first before '.tr(),
confirmButtonText: 'sure'.tr(),
declineButtonText: 'cancel'.tr(),
onDecline: () {
Navigator.pop(context);
},
onConfirm: onDeclineConfirmed,
additionalWidget: Column(
children: [
ReusableDropdownButton(
itemList: itemList,
width: 197,
height: 26,
onChanged: (newValue) {
setState(() {
selectedReason = newValue;
});
},
),
const SizedBox(height: 10),
if (selectedReason == 'Alasan lainnya')
Container(
constraints: const BoxConstraints(minHeight: 78),
width: 230,
decoration: BoxDecoration(
color: othersChatColor,
borderRadius: BorderRadius.circular(15),
),
padding:
const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: TextFormField(
controller: ticketTextController,
maxLength: 100,
inputFormatters: [
LengthLimitingTextInputFormatter(1000),
],
style: primaryColor400Style.copyWith(
fontSize: fontSize11,
),
maxLines: null,
keyboardType: TextInputType.multiline,
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
border: InputBorder.none,
hintText: 'reasonHint'.tr(),
hintStyle: weight400Style.copyWith(
color: hintColor, fontSize: fontSize11),
counterText: '',
),
),
),
const SizedBox(height: 5),
],
),
);
});
}

Because the dialog and bottom sheets don't have states so you must create a different stateful widget for the widget you want to show in the dialog or sheet and then return it from the dialog or bottom sheet. that's how it will work as a stateful widget and will update as you want.
void rejectDialog(
{required dynamic ticketData,
required String ticketId,
required VoidCallback onDeclineConfirmed}) {
showDialog(
context: context,
builder: (context) {
return StateFulWidgetYouCreate();
});
}

Related

Flutter AutoComplete Widget, not letting me choose text outside of an Array

My code is as follows:
final TextEditingController _locationController = TextEditingController();
late TextEditingController myController;
late List<String> locationSuggestions; // Populated with options in code first
Autocomplete<String>(
initialValue: TextEditingValue(text:_locationController.text),
optionsMaxHeight: 50,
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text.isEmpty) return const Iterable<String>.empty();
return locationSuggestions.where((String option) {
return option
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
optionsViewBuilder: (context, onSelected, options){
return Material(
elevation: 8,
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 0.0),
itemBuilder: (BuildContext context, int index) {
final String option = options.elementAt(index);
return ListTile(
dense: true,
// tileColor: Colors.deepOrange,
title: SubstringHighlight(
text: option,
term: myController.text,
textStyleHighlight: const TextStyle(fontWeight: FontWeight.w700, fontSize: 16.0),
),
onTap: () => onSelected(option),
);
},
separatorBuilder: (context, index) => const Divider(),
itemCount: options.length,
));
},
onSelected: (String value)=> myController.text = value,
fieldViewBuilder: (context, controller, focusNode, onEditingComplete){
myController = controller;
return TextFormField(
controller: myController,
focusNode: focusNode,
maxLines: 1,
maxLength: 30,
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Location',
prefixIcon: Icon(
Icons.add_location,
size: 35.0,
color: Theme.of(context).colorScheme.primary,
)),
onEditingComplete: onEditingComplete,
//onTap: ()=>FocusManager.instance.primaryFocus?.unfocus(),
);
},
),
The Problem:
When I go and type the text, I see options appearing below, if I choose one of the options, all goes well and good.
BUT... I am not able to type a new 'similar' custom option. So for example, if I get a suggestion for the word 'Apple' and I just want to stop typing at App, I can't do it. The done button on the keyboard does not hide the keyboard and if I try to move away from the field the entire 'Apple' appears in the text field. I tried experimenting with unfocus but it is not the right way and I am sure I am missing a feature here.

Good way to mange state inside dialog with a form on it, being displayed from page with its own bloc?

See for the invoice page I have BlocBuilder wrapped in a scaffold of stateful page, inside that body under several widgets is a call to future void in separate file call to create a dialog widget. And inside the dialog method is a call to create an invoice form which is in a separate file and is stateful class displayed to be displayed on the dialog screen. In this form the user will be able to add and delete UI elements from a list view what I need to do is rebuild the widget either dialog screen/form or the list view/ to reflect the changes made by the user
import 'package:flutter/material.dart';
import 'dart:developer' as dev;
import 'package:track/src/features/invoices/application/bloc.dart';
import 'package:track/src/features/invoices/application/events.dart';
import 'package:track/src/features/invoices/application/pdf_invoice_api.dart';
class InvoiceForm extends StatefulWidget {
final InvoiceBlocController blocController;
const InvoiceForm(this.blocController, {Key? key}) : super(key: key);
#override
State<InvoiceForm> createState() => _InvoiceFormState();
}
class _InvoiceFormState extends State<InvoiceForm> {
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: TextEditingController()
..text = widget.blocController.invoice.client,
validator: (value) {
value!.isEmpty ? 'Enter a value for client' : null;
},
style: Theme.of(context).textTheme.labelMedium,
decoration: InputDecoration(
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
enabledBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
labelText: 'Client:',
labelStyle: Theme.of(context).textTheme.labelMedium),
),
TextFormField(
controller: TextEditingController()
..text =
'${widget.blocController.invoice.projectNumber}-${widget.blocController.invoice.invoiceNumber}',
validator: (value) {
value!.isEmpty ? 'Enter a valid project number' : null;
},
style: Theme.of(context).textTheme.labelMedium,
decoration: InputDecoration(
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
enabledBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
labelText: 'Client:',
labelStyle: Theme.of(context).textTheme.labelMedium),
),
ListView.builder(
shrinkWrap: true,
itemCount: widget.blocController.invoice.items.length,
itemBuilder: (context, index) {
final item = widget.blocController.invoice.items[index];
return ListTile(
contentPadding: EdgeInsets.zero,
trailing: IconButton(
onPressed: () {
widget.blocController.add(DeleteItemFromInvoice(index));
},
icon: Icon(Icons.delete)),
title: Column(
children: [
Row(
children: [
itemTextFormField(
initialValue: item.name ?? '',
labelText: 'name',
index: index),
SizedBox(width: 20),
itemTextFormField(
initialValue: item.description ?? '',
labelText: 'description',
index: index),
],
),
Row(
children: [
itemTextFormField(
initialValue: item.quantity.toString(),
labelText: 'quantity',
index: index),
SizedBox(width: 20),
itemTextFormField(
initialValue: item.costBeforeVAT.toString(),
labelText: 'Cost Before VAT',
index: index),
],
),
SizedBox(height: 30),
Divider(
thickness: 2,
color: Colors.black,
)
],
),
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
dev.log('button clicked to add new item');
widget.blocController.add(AddNewItemToInvoice());
},
icon: Icon(Icons.add)),
IconButton(
onPressed: () async {
_formKey.currentState!.save();
Navigator.pop(context);
await PdfInvoiceApi.generate(widget.blocController.invoice);
},
icon: Icon(Icons.send))
],
)
],
),
);
}
Expanded itemTextFormField({
required String initialValue,
required String labelText,
required int index,
}) {
return Expanded(
child: TextFormField(
controller: TextEditingController()..text = initialValue,
onSaved: (newValue) {
widget.blocController.add(UpdateInvoiceDetails(index));
},
style: Theme.of(context).textTheme.labelMedium,
decoration: InputDecoration(
focusedBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
enabledBorder: const UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
),
),
labelText: labelText,
labelStyle: Theme.of(context).textTheme.labelMedium,
),
),
);
}
}
InvoiceDialog Source code: https://pastebin.com/PCjmCWsk
InvoiceDialog Source code: https://pastebin.com/VS5CG22D
Edit 2: Made the follwoing changes to bloc per Mostafa answer as best I could, getting pressed against a deadline here so really need some help:
These changes were to main page calling the show dialog passing bloc.
showDialog(
context: context,
builder: (context) => BlocProvider.value(
value: blocController,
child: InvoiceDetailsDialog(
screenWidth: screenWidth,
screenHeight: screenHeight),
),
);
This file was the original place where showdialog was called and was custom Future return showDialog.
Results: showDialog takes enitre screen. Rendering Invoice form reulsts in error being displayed in place of the form:
No Material widget found.
Edit 3: fixed previous error but back where i started bloc is still being called succesfully but no changes to the ui:
Widget build(BuildContext context) {
final blocController = BlocProvider.of<InvoiceBlocController>(context);
return Center(
child: Material(color: Colors.red,
borderRadius: BorderRadius.circular(50),
child: SizedBox(
width: screenWidth / 2, height: screenHeight / 2,
child: Padding(padding: const EdgeInsets.all(20),
child: Column(children: [
Expanded(child: ListView(children: [
Text('Invoices',
style: Theme.of(context)
.textTheme.bodyLarge?.copyWith(color: Colors.white)),
InvoiceForm()
]))])))));
}
As form nothing changed except instead of passing the blocController through a method I am now calling it like:
class _InvoiceFormState extends State<InvoiceForm> {
final _formKey = GlobalKey<FormState>();
late final InvoiceBlocController blocController;
#override
void initState() {
blocController = BlocProvider.of<InvoiceBlocController>(context);
super.initState();
}
Still nothing changes.
Edit 4: Set state does work and leaving in bloc code was executing and if I clicked add two items would be added or delete would remove two items. But with setstate commented out it went back to not rebuilding. Using setstate for now but not preferred.
Edit 5: Don't if this is still being paid attention to hopefully is. Can I keep add add events like: add(NewItem), add(deleteItem),add(GeneratePDF). Without changing state. currently I have done that once so far. Is this bad practice
You can pass the main bloc to the dialog widget and call the bloc function that you want and it will reflect on the main screen
How can you do this? by injecting the MainBloc value to DialogWidget with BlocProvider.value
MainWidget
class MainWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider(
create: (BuildContext context) => MainBloc(),
child: BlocConsumer<MainBloc, MainStates>(
listener: (BuildContext context, MainStates state) {},
builder: (BuildContext context, MainStates state) {
final bloc = MainBloc.get(context);
return GestureDetector(
onTap: () {
showDialog(
context,
builder: (context) => BlocProvider.value(
value: bloc,
child: WidgetTwoDialog(),
),
);
},
child: Item(),
);
},
),
);
}
}
DialogWidget
class DialogWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
final bloc = MainBloc.get(context);
return GestureDetector(
onTap: () {
bloc.addToList();
},
child: Text('Remove form the main screen'),
);
}
}
Also, this answer might help you to get my point well here
you can wrap your dialog within the stateful builder and then you will get the method to set your dialog state.

I am not able to access TextEditingController using bloc in Flutter

How to access TextEditingController(); using bloc . here my code :-
after i use
BlocProvider.of<UsernameupdateCubit>(context).nameUpdate(userUpdateController.text);
I got an error which is
BlocProvider.of() called with a context that does not contain a UsernameupdateCubit.
Please check :
I use
final userUpdateController = TextEditingController();
then
TextFormField(
controller: userUpdateController,
decoration: InputDecoration(
labelText: "Full Name",
border: OutlineInputBorder(),
prefixIcon: Icon(FeatherIcons.user, size: 24),
),
),
after that use a button to save/sent/access anywhere or display in list view :
button is :
Container(
margin: EdgeInsets.only(top: 10),
alignment: AlignmentDirectional.centerEnd,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 1,
primary: Color(0xff34495e),
),
onPressed: () {
// BlocProvider.of<UsernameupdateCubit>(context).nameUpdate();
// BlocProvider.of<WeatherBloc>(context)
BlocProvider.of<UsernameupdateCubit>(context)
.nameUpdate(userUpdateController.text);
},
child: Text(
"Continue",
),
),
),
My Cubit :
class UsernameupdateCubit extends Cubit<UsernameupdateState> {
UsernameupdateCubit() : super(UsernameupdateState(userUpdateName: ''));
void nameUpdate(userUpdateController) =>
emit(UsernameupdateState(userUpdateName: userUpdateController.text));
}
and state is :
class UsernameupdateState {
String userUpdateName;
UsernameupdateState({
required this.userUpdateName,
});
}
all are same but I include BlocProvider in :
using multibloc:
BlocProvider(
create: (context) => UsernameupdateCubit(),
),
after that I changed my cubit :
void nameUpdate(userUpdateController) =>
emit(UsernameupdateState(userUpdateName: userUpdateController));
and yes that's it .
thank you – #nvoigt #nvoigt

Deleting specific item out of ListView with Bloc

I have a page that consists of a ListView, which contains TextFormFields. The user can add or remove items from that ListView.
I use the bloc pattern, and bind the number of Items and their content inside the ListView to a list saved in the bloc state. When I want to remove the items, I remove the corresponding text from this list and yield the new state. However, this will always remove the last item, instead of the item that's supposed to be removed. While debugging, I can clearly see that the Item I want removed is in fact removed from the state's list. Still, the ListView removes the last item instead.
I've read that using keys solves this problem and it does. However, if I use keys there is a new problem.
Now, the TextFormField will go out of focus every time a character is written. I guess this is to do with the fact that the ListView is redrawing its items everytime a character is typed, and somehow having a key makes the focus behave differently.
Any ideas how to solve this?
The page code (The ListView is at the bottom):
class GiveBeneftis extends StatelessWidget {
#override
Widget build(BuildContext context) {
var bloc = BlocProvider.of<CreateChallengeBloc>(context);
return BlocBuilder<CreateChallengeBloc, CreateChallengeState>(
builder: (context, state) {
return CreatePageTemplate(
progress: state.progressOfCreation,
buttonBar: NavigationButtons(
onPressPrevious: () {
bloc.add(ProgressOfCreationChanged(nav_direction: -1));
Navigator.of(context).pop();
},
onPressNext: () {
bloc.add(ProgressOfCreationChanged(nav_direction: 1));
Navigator.of(context).pushNamed("create_challenge/add_pictures");
},
previous: 'Details',
next: 'Picture',
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'List the benefits of you Challenge',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
SizedBox(height: 30),
Text(
'Optionally: Make a list of physical and mental benefits the participants can expect. ',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.grey,
fontSize: 14,
fontWeight: FontWeight.w400),
),
SizedBox(height: 50),
Container(
margin: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.yellow[600]),
child: FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onPressed: () => bloc.add(ChallengeBenefitAdded()),
child: Text('Add a benefit',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
),
),
Expanded(
child: new ListView.builder(
itemCount: state.benefits.length,
itemBuilder: (BuildContext context, int i) {
final item = state.benefits[i];
return Padding(
padding: EdgeInsets.symmetric(horizontal: 25),
child: TextFieldTile(
//key: UniqueKey(),
labelText: 'Benefit ${i + 1}',
validator: null,
initialText: state.benefits[i],
onTextChanged: (value) => bloc.add(
ChallengeBenefitChanged(
number: i, text: value)),
onCancelIconClicked: () {
bloc.add(ChallengeBenefitRemoved(number: i));
},
));
})),
],
),
);
});
}
}
The Code of the TextfieldTile:
class TextFieldTile extends StatelessWidget {
final Function onTextChanged;
final Function onCancelIconClicked;
final Function validator;
final String labelText;
final String initialText;
const TextFieldTile(
{Key key,
this.onTextChanged,
this.onCancelIconClicked,
this.labelText,
this.initialText,
this.validator})
: super(key: key);
#override
Widget build(BuildContext context) {
return Stack(children: <Widget>[
TextFormField(
textCapitalization: TextCapitalization.sentences,
initialValue: initialText,
validator: validator,
onChanged: onTextChanged,
maxLines: null,
decoration: InputDecoration(
labelText: labelText,
)),
Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(Icons.cancel), onPressed: onCancelIconClicked),
),
]);
}
}
The relevant portion of the Bloc:
if (event is ChallengeBenefitAdded) {
var newBenefitsList = List<String>.from(state.benefits);
newBenefitsList.add("");
yield state.copyWith(benefits: newBenefitsList);
}
else if (event is ChallengeBenefitChanged) {
var newBenefitsList = List<String>.from(state.benefits);
newBenefitsList[event.number] = event.text;
yield state.copyWith(benefits: newBenefitsList);
}
else if (event is ChallengeBenefitRemoved) {
var newBenefitsList = List<String>.from(state.benefits);
newBenefitsList.removeAt(event.number);
yield state.copyWith(benefits: newBenefitsList);
}
I can think of two things you can do here.
Create a different bloc for processing the changes in the text field, that will avoid having to actually update the state of the entire list if no needed.
Have a conditional to avoid rebuilding the list when your bloc change to a state that is relevant only to the keyboard actions.
Example:
BlocBuilder<CreateChallengeBloc, CreateChallengeState>(
buildWhen: (previousState, currentState) {
return (currentState is YourNonKeyboardStates);
}
...
);

Is there a way which helps the keyboard focus correctly on the textformfield

I write an android app with flutter. As a part of my code I created a user page to let the user to update their information such as name surname or something like that.
It is working but when I clicked the page I am getting few errors.
1 is I/ple.flutter_ap(18747): The ClassLoaderContext is a special shared library.
2nd is W/ple.flutter_ap(18747): Accessing hidden field Ldalvik/system/BaseDexClassLoader;->pathList:Ldalvik/system/DexPathList; (light greylist, reflection)
And the other problem is The keyboard is not focusing on the textfield. When I clicked the textfield the keyborad is Opening and closing immediately. When I clicked again it shows up and again closing immediately.
I tried autofocus: true but this time it tried to focus it self. It is opended and closed 5 times but at last it focused. But that shouldnt be happen.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Screen1 extends StatefulWidget {
#override
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
var _AdContr = TextEditingController();
var _SoyadContr = TextEditingController();
final _NicknameContr = TextEditingController();
final _getContr = TextEditingController();
final _myUpdateContr = TextEditingController();
var _transactionListener;
#override
void dispose() {
// Clean up controllers when disposed
_AdContr.dispose();
_SoyadContr.dispose();
_NicknameContr.dispose();
_getContr.dispose();
_myUpdateContr.dispose();
// Cancel transaction listener subscription
_transactionListener.cancel();
super.dispose();
}
void clickUpdate(_formKey1, _formKey2) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String uid = user.uid.toString();
await Firestore.instance
.collection('kitaplar')
.document(uid)
.updateData({'adi': _formKey1, 'Soyadi': _formKey2});
Navigator.pop(context);
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: new Container(
padding: EdgeInsets.only(top: 20.0, left: 10.0, right: 10.0),
child: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context,
AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.connectionState != ConnectionState.done)
return Container();
return StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance.collection('kitaplar')
.document(snapshot.data.uid)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) return Container();
var userDocument = snapshot.data;
var contentadi = userDocument["adi"].toString();
var contentsoyadi = userDocument["Soyadi"].toString();
return Column(
children: <Widget>[
TextFormField(
controller: _AdContr = new TextEditingController(text: contentadi == null ? "" : contentadi),
//controller: _AdContr,
//initialValue: userDocument["adi"].toString(),
decoration: new InputDecoration(
labelText: 'Adınız',
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
),
SizedBox(height: 20),
TextFormField(
controller: _SoyadContr = new TextEditingController(text: contentsoyadi == null ? "" : contentsoyadi),
//controller: _AdContr,
decoration: new InputDecoration(
labelText: 'Soyadınız',
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
),
RaisedButton(
color: Colors.orange,
textColor: Colors.white,
splashColor: Colors.orangeAccent,
child: const Text('Update'),
onPressed: () {
clickUpdate(_AdContr.text, _SoyadContr.text);
},
),
],
);
},
);
})
)
);
}
}
How do I solve this problem?
To foucs on next text input field you have to use "FocusNode();" such as below:
In the "TextFormField(" we can use this method to focus:
onFieldSubmitted: (v){
FocusScope.of(context).requestFocus(focus);
},
Also to set different options for text input field such as next and done options in keyboard, you can use below method:
1) For next option: "textInputAction: TextInputAction.next,"
2) For done option: "textInputAction: TextInputAction.done,"
Below is the full example to auto focus on next text input field:
class MyApp extends State<MyLoginForm> {
final _formKey = GlobalKey<FormState>();
final focus = FocusNode();
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 30, top: 65.0, right: 30, bottom: 0),
child:
TextFormField(
textInputAction: TextInputAction.next,
decoration: new InputDecoration(hintText: 'Enter username', contentPadding: EdgeInsets.all(8.0)),
style: new TextStyle(fontSize: 18),
onFieldSubmitted: (v){
FocusScope.of(context).requestFocus(focus);
},
),
),
Padding(
padding: const EdgeInsets.only(left: 30, top: 30.0, right: 30, bottom: 0),
child:
TextFormField(
focusNode: focus,
textInputAction: TextInputAction.done,
decoration: new InputDecoration(hintText: 'Enter password', contentPadding: EdgeInsets.all(8.0)),
style: new TextStyle(fontSize: 18),
onFieldSubmitted: (v){
FocusScope.of(context).requestFocus(focus);
},
),
),
],
),
),
),
);
}
}
Problem is you are setting the text in TextFormField when keyboard opens with the TextEditingController. It means
you are assigning a value every time in TextEditingController so when keyboard opens, "TextEditingController" will
fire and it will try to check your condition and set the default value in your TextFormField and then keyboard gets
closed as normal behaviour.
So to solve this do as below:
First of all initialize your "TextEditingController" with "new" keyboard as below:
var _AdContr = new TextEditingController();
var _SoyadContr = new TextEditingController();
final _NicknameContr = new TextEditingController();
final _getContr = new TextEditingController();
final _myUpdateContr = new TextEditingController();
Then try to set default text for "TextFormField" after this two lines:
var contentadi = userDocument["adi"].toString();
var contentsoyadi = userDocument["Soyadi"].toString();
_AdContr.text = (contentadi == null ? "" : contentadi);
_SoyadContr.text = (contentsoyadi == null ? "" : contentsoyadi);
Then change your "TextFormField" as below and try to save those value in your variables in "onSubmitted" method:
return Column(
children: <Widget>[
TextFormField(
controller: _AdContr,
onSubmitted: (String str){
setState(() {
contentadi = str;
_AdContr.text = contentadi;
});
},
decoration: new InputDecoration(
labelText: 'Adınız',
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
),
SizedBox(height: 20),
TextFormField(
controller: _SoyadContr,
onSubmitted: (String str){
setState(() {
contentsoyadi = str;
_SoyadContr.text = contentsoyadi;
});
},
decoration: new InputDecoration(
labelText: 'Soyadınız',
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
),
RaisedButton(
color: Colors.orange,
textColor: Colors.white,
splashColor: Colors.orangeAccent,
child: const Text('Update'),
onPressed: () {
clickUpdate(_AdContr.text, _SoyadContr.text);
},
),
],
);
If above solution not work then try to use StreamBuilder() instead of FutureBuilder(). it will work and focuse without any problem.