TextField values are dissapeared? - flutter

I started learning flutter recently. In my app window when I push a button a bottom sheet modal will appear like in the below image. When I typing in the 'Amount' text field, the previously typed 'Title' text filed content is disappeared. Why is this happen and how to solve this?
This my code related to read text field inputs.
import 'dart:io';
import './adaptive_flat_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatelessWidget {
final Function newTransactionHandler;
final titleController = TextEditingController();
final amountController = TextEditingController();
DateTime selectedDate;
NewTransaction(this.newTransactionHandler);
void addTx() {
if (amountController.text.isEmpty) {
return;
}
String titileTxt = titleController.text;
double amount = double.parse(amountController.text);
if (titileTxt.isEmpty || amount <= 0 || selectedDate == null) {
return;
}
newTransactionHandler(titileTxt, amount, selectedDate);
Navigator.of(context).pop();
}
void presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
}
selectedDate = pickedDate;
});
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Card(
elevation: 5,
child: Container(
padding: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
bottom: MediaQuery.of(context).viewInsets.bottom + 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: titleController,
onSubmitted: (_) => addTx(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: amountController,
keyboardType: TextInputType.phone,
onSubmitted: (_) => addTx(),
// onChanged: (val) {
// amountInput = val;
// },
),
Container(
height: 70,
child: Row(
children: [
Text(selectedDate == null
? 'No date chosen!'
: 'PickedDate: ${DateFormat.yMd().format(selectedDate)}'),
AdaptiveFlatButton('Choose Date', presentDatePicker),
],
),
),
RaisedButton(
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
child: Text(
'Add Transaction',
),
onPressed: addTx,
)
],
),
),
),
);
}
}

I solved this issue by just replacing StatelessWidget with StatefulWidget.
import 'dart:io';
import './adaptive_flat_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function newTransactionHandler;
NewTransaction(this.newTransactionHandler) {
print('Constructor NewTRansaction');
}
#override
_NewTransactionState createState() {
print('CreateState NewTransaction');
return _NewTransactionState();
}
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime selectedDate;
_NewTransactionState() {
print('Constructor NewTransaction State');
}
#override
void initState() {
// TODO: implement initState
print('initState()');
super.initState();
}
#override
void didUpdateWidget(covariant NewTransaction oldWidget) {
// TODO: implement didUpdateWidget
print('didUpdate()');
super.didUpdateWidget(oldWidget);
}
#override
void dispose() {
// TODO: implement dispose
print('dispose()');
super.dispose();
}
void _addTx() {
if (_amountController.text.isEmpty) {
return;
}
String titileTxt = _titleController.text;
double amount = double.parse(_amountController.text);
if (titileTxt.isEmpty || amount <= 0 || selectedDate == null) {
return;
}
widget.newTransactionHandler(titileTxt, amount, selectedDate);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Card(
elevation: 5,
child: Container(
padding: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
bottom: MediaQuery.of(context).viewInsets.bottom + 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _addTx(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.phone,
onSubmitted: (_) => _addTx(),
// onChanged: (val) {
// amountInput = val;
// },
),
Container(
height: 70,
child: Row(
children: [
Text(selectedDate == null
? 'No date chosen!'
: 'PickedDate: ${DateFormat.yMd().format(selectedDate)}'),
AdaptiveFlatButton('Choose Date', _presentDatePicker),
],
),
),
RaisedButton(
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
child: Text(
'Add Transaction',
),
onPressed: _addTx,
)
],
),
),
),
);
}
}

You can't use setState in Stateless Widget
Just refractor with right click on StatelessWidget, select refractor then select Convert to StatefulWidget

Related

How can I solve this problem that two keyboard cursors in textfield?

https://i.stack.imgur.com/YKClg.png
I have multiple textfields and I have written code that expects that clearing index 0, i.e. the first textfield in the list, will set the focus back to the first textfield, but contrary to expectations, the cursor moves to the second field. text field. , and why do I see two cursors when I click on another textfield in this state?
`
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:todolist/dataForm.dart';
class TodoCase extends StatefulWidget {
final String title;
const TodoCase({
Key? key,
required this.title,
}) : super(key: key);
#override
State<TodoCase> createState() => _TodoCaseState();
}
class _TodoCaseState extends State<TodoCase> {
List<ToDoDataForm> toDoLineList = [];
final FocusScopeNode textListScopeNode = FocusScopeNode();
final ScrollController toDoScrollController = ScrollController();
List<TextEditingController> textEditController = [];
List<FocusNode> keyBoardFocusNode = [];
List<FocusNode> textFocusNode = [];
Future<void> scrollToEnd() async {
await Future.delayed(const Duration(milliseconds: 100));
toDoScrollController.animateTo(
toDoScrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 400),
curve: Curves.ease,
);
}
#override
Widget build(BuildContext context) {
void addList() {
setState(() {
toDoLineList.add(ToDoDataForm(todoData: ""));
scrollToEnd();
});
}
Widget renderTextFormField(ToDoDataForm dataForm, int index) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Checkbox(
value: dataForm.isDone,
onChanged: (value) {
setState(() {
dataForm.isDone = value!;
});
}),
Flexible(
child: KeyboardListener(
focusNode: keyBoardFocusNode[index],
onKeyEvent: (value) {
if (value.logicalKey == LogicalKeyboardKey.backspace &&
dataForm.todoData.isEmpty) {
setState(() {
if (index != 0) {
textFocusNode[index - 1].requestFocus();
toDoLineList.removeAt(index);
textFocusNode.removeAt(index);
keyBoardFocusNode.removeAt(index);
textEditController.removeAt(index);
} else if (index == 0 && toDoLineList.length == 1) {
toDoLineList.removeAt(index);
textFocusNode.removeAt(index);
textEditController.removeAt(index);
keyBoardFocusNode.removeAt(index);
} else if (index == 0 && toDoLineList.length != 1) {
FocusScope.of(context)
.requestFocus(textFocusNode[index + 1]);
toDoLineList.removeAt(index);
textFocusNode.removeAt(index);
textEditController.removeAt(index);
keyBoardFocusNode.removeAt(index);
}
});
print(textFocusNode);
}
},
child: TextField(
decoration: const InputDecoration(
border: InputBorder.none,
),
autofocus: false,
controller: textEditController[index],
focusNode: textFocusNode[index],
onChanged: (value) {
//print('edit : $index');
dataForm.todoData = value;
//print(textFocusNode);
},
),
),
)
],
);
}
return SizedBox(
width: 180,
height: 200,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
widget.title,
style: const TextStyle(
color: Colors.black,
fontSize: 24,
),
),
IconButton(
onPressed: addList,
icon: const Icon(Icons.add),
padding: EdgeInsets.zero,
iconSize: 20,
),
],
),
Container(
height: 1,
color: Colors.black,
),
Expanded(
child: ListView.builder(
itemCount: toDoLineList.length,
controller: toDoScrollController,
itemBuilder: ((context, index) {
if (textEditController.length - 1 < index) {
print(index);
textEditController.add(TextEditingController(
text: toDoLineList[index].todoData));
textFocusNode.add(FocusNode());
textFocusNode[index].unfocus();
keyBoardFocusNode.add(FocusNode());
}
print(index);
print(textFocusNode);
return renderTextFormField(toDoLineList[index], index);
}),
),
),
],
),
);
}
}
`
i try to focusNode List move to glover and textfield wrap FocusScopeNode and many try things but i can't solve this problem...

how to make a button disable in flutter

I'am trying to create a profile form . I want to disable or enable the button based on the validation. I tried to check the currentstate of form validated or not. it is working fine but when i type on one of the textFormField , I am getting error message on all of the textFormField .
Here is the code i'am working.
import 'dart:html';
import 'package:flutter/material.dart';
class ProfileForm extends StatefulWidget {
const ProfileForm({Key? key}) : super(key: key);
#override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final _formKey = GlobalKey<FormState>();
DateTime selectedDate = DateTime.now();
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _dobController = TextEditingController();
final _currentLocationController = TextEditingController();
final _locationIndiaController = TextEditingController();
bool btndisable = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
RegExp emailValidator = RegExp(
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
onChanged: () {
notdisbled();
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Let’s create a profile for you",
style: AppTextStyleSecondary.headline2sec,
),
const SizedBox(
height: 12,
),
Padding(
padding: const EdgeInsets.only(right: 100.0),
child: Text(
"Please enter your personal details",
),
),
const SizedBox(
height: 16,
),
Text("Your name"),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (val) {
},
validator: (val) {
if (val.toString().length < 2) {
return "Please enter your name";
}
return null;
},
controller: _nameController,
decoration: const InputDecoration(
isDense: true,
contentPadding:
EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
),
Text(labelText: "Date of Birth"),
InkWell(
child: TextFormField(
onTap: () {
_selectDate(context);
},
validator: (val) {
if (val.toString().isEmpty) {
return "This field is required";
} else {
return null;
}
},
readOnly: true,
controller: _dobController,
),
),
Text("Email address"),
TextFormField(
controller: _emailController,
onChanged: (val) {},
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (val) {
String email = val!.trim();
if (emailValidator.hasMatch(email)) {
return null;
} else {
return "Enter valid email address";
}
},
decoration: const InputDecoration(
isDense: true,
contentPadding:
EdgeInsets.symmetric(horizontal: 10, vertical: 12)),
),
Text(labelText: "Your location where you currently live"),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (val) {
if (val.toString().isEmpty) {
return "This field is required";
} else {
return null;
}
},
onChanged: (val) {
},
controller: _currentLocationController,
),
Text("Your location in India"),
TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (val) {
if (val.toString().isEmpty) {
return "This field is required";
} else {
return null;
}
},
onChanged: (val) {},
controller: _locationIndiaController,
),
const SizedBox(
height: 25,
),
Container(
width: double.infinity,
height: 45,
decoration: BoxDecoration(
color: btndisable ? Colors.blue : Colors.red,
borderRadius: BorderRadius.circular(8),
),
child: TextButton(
onPressed: (){
if(_formKey.currentState!.validate()){
Navigator.of(context).pushNamedAndRemoveUntil(
'HomeScreen', (Route<dynamic> route) => false);
}
}
child: Text("Continue"),
),
),
const SizedBox(
height: 20,
),
],
),
),
)),
);
}
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(1970),
lastDate: DateTime(2101));
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
_dobController.text =
"${selectedDate.day}/${selectedDate.month}/${selectedDate.year}";
});
}
}
void notdisbled() {
if (_formKey.currentState!.validate() == false) {
setState(() {
btndisable = false;
});
} else {
setState(() {
btndisable = true;
});
}
}
}
for disable the button change to this :
child: TextButton(
onPressed: _formKey.currentState != null && _formKey.currentState.validate() ? () {
Navigator.of(context).pushNamedAndRemoveUntil(
'HomeScreen', (Route<dynamic> route) => false);
}: null,
child: AppText(
text: "Continue",
fontSize: 16,
fontWeight: FontWeight.bold,
color: AppColor.white),
),
but when you use
formKey.currentState!.validate()
when you type any thing, flutter try call it every time so your form widget run all validator func in all its textfield. so it is natural for all textfield to get error message

Non-nullable instance field '_selectedDate' must be initialized

I am developing an Expenses Management App in flutter, Here I am trying to create a DateTimePicker using showDatePicker(). therefore Inside my presentDateTimePicker() function i am calling showDatePicker() method.
and I am creating a variable for selectedDate where I am not initializing it to a current value since it will change based on the user input.
Inside my setState() method I use _selectedDate = pickedDate.
Still, it shows an error saying "non-nullable instance field"
My widget
//flutter imports
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
final _brandNameControlller = TextEditingController();
DateTime _selectedDate;
void _submitData() {
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
final enteredBrandName = _brandNameControlller.text;
if (enteredTitle.isEmpty || enteredAmount <= 0) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
enteredBrandName,
);
Navigator.of(context).pop();
}
void _presentDateTimePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData,
//onChanged: (val) {
//titleInput = val;
//},
),
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData,
//onChanged: (val) => amountInput = val,
),
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Brand Name'),
controller: _brandNameControlller,
onSubmitted: (_) => _submitData,
//onChanged: (val) => brandInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}'),
FlatButton(
onPressed: _presentDateTimePicker,
child: Text(
'Chose Date',
style: TextStyle(fontWeight: FontWeight.bold),
),
textColor: Theme.of(context).primaryColor,
),
],
),
),
RaisedButton(
onPressed: _submitData,
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button!.color,
),
],
),
),
);
}
}
If the value is nullable just mark the variable as such DateTime? _selectedDate;
And whenever you would use it just check for null first:
Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),
// Here you do know that the value can't be null so you assert to the compiler that
Check out the official docs on null safety they are extremely high quality and instructive.
There you can read about when to use nullable ? non nullable or late variables.
There is a work around in this situation
initialize the date with
DateTime _selectedDate = DateTime.parse('0000-00-00');
and later on in text widget
instead of
Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),
use
Text(_selectedDate == DateTime.parse('0000-00-00')
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),
If you will change the value in the setState method, you can initialize the variable with
DateTime _selectedDate = DateTime.now();
and format it to the format you show the user, this would get rid of the error and if you are going to change it each time the user selects a date, seeing the current date as a starting value gives the user a starting point as a reference.
step1 : Put a question mark '?' after DateTime data type such as DateTime? _selectedDate;
Adding a question mark indicates to Dart that the variable can be null. I expect that initially the _selectedDate is not set, so Dart is giving an error warning due to null-safety. By putting a question mark in the type, you are saying you expect that the variable can be null (which is why it fixes the error).
step2 : whenever you would use it just check for null first by adding a null check (!)
After fixing errors your code is now :
//flutter imports
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
final _brandNameControlller = TextEditingController();
DateTime? _selectedDate;
void _submitData() {
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
final enteredBrandName = _brandNameControlller.text;
if (enteredTitle.isEmpty || enteredAmount <= 0) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
enteredBrandName,
);
Navigator.of(context).pop();
}
void _presentDateTimePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData,
//onChanged: (val) {
//titleInput = val;
//},
),
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData,
//onChanged: (val) => amountInput = val,
),
TextField(
autocorrect: true,
decoration: InputDecoration(labelText: 'Brand Name'),
controller: _brandNameControlller,
onSubmitted: (_) => _submitData,
//onChanged: (val) => brandInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Text(_selectedDate == null
? 'No Date Chosen'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate!)}'),
FlatButton(
onPressed: _presentDateTimePicker,
child: Text(
'Chose Date',
style: TextStyle(fontWeight: FontWeight.bold),
),
textColor: Theme.of(context).primaryColor,
),
],
),
),
RaisedButton(
onPressed: _submitData,
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button!.color,
),
],
),
),
);
}
}

Validator works for all fields except one in flutter

I have a screen to add a customer's details. Name, company, mobile no.,email,profile picture. I have added validator to all the fields. Validator is working for all the fields but not for one field, the top one(Name). I dont know why. When I place the field below all the fields then the validator works but I want to keep the field on top. I want Name field to contain some value.
add_person.dart
import 'dart:io';
import 'package:email_validator/email_validator.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/language.dart';
import 'package:vers2cts/models/languages_widget.dart';
import 'package:vers2cts/models/languages_model.dart';
import 'package:vers2cts/screens/people_list.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_helper.dart';
import 'search_contacts.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
class AddPerson extends StatefulWidget {
String uname;
final String appBarTitle;
final CustomerModel customer;
AddPerson(this.uname,this.customer,this.appBarTitle);
#override
State<StatefulWidget> createState() {
return AddPersonState(uname,customer,appBarTitle);
}
}
class AddPersonState extends State<AddPerson> {
GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
String uname,email,mobnum;
AddPersonState(this.uname,this.customer,this.appBarTitle);
bool engcheckbox=false;
String appBarTitle;
CustomerModel customer=new CustomerModel();
LanguagesModel langs=new LanguagesModel();
DBService dbService=new DBService();
bool showPassword = false;
DateTime _date=DateTime.now();
TextEditingController datefield=TextEditingController();
PickedFile _imageFile;
final ImagePicker _picker=ImagePicker();
TextEditingController custfNameController = TextEditingController();
TextEditingController custlNameController = TextEditingController();
TextEditingController custMobileNoController = TextEditingController();
TextEditingController custCompanyController = TextEditingController();
TextEditingController addrController = TextEditingController();
TextEditingController custEmailController = TextEditingController();
void getImage(ImageSource source) async{
final pickedFile=await _picker.getImage(
source:source);
setState(() {
_imageFile=pickedFile;
customer.cust_photo = _imageFile.path;
});
}
Future<Null> _selectDate(BuildContext context)async {
DateTime _datePicker = await showDatePicker(
context: context,
initialDate: _date,
firstDate: DateTime(1947),
lastDate: DateTime(2030),);
if (_datePicker != null && _datePicker != _date) {
setState(() {
_date = _datePicker;
String formattedDate = DateFormat('dd-MM-yyyy').format(_date);
datefield.text=formattedDate.toString();
print(datefield.text);
});
}
}
#override
Widget build(BuildContext context){
var selectedLanguages = languages.where((element) => element.selected);
TextStyle textStyle=Theme.of(context).textTheme.title;
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
var _minimumPadding = 5.0;
custfNameController.text = customer.first_name;
custlNameController.text = customer.last_name;
custMobileNoController.text = customer.mob_num;
custCompanyController.text=customer.org_name;
addrController.text=customer.addr;
custEmailController.text=customer.email_id;
return WillPopScope(
onWillPop: () {
moveToLastScreen();
},
child: Scaffold(
appBar: AppBar(
title: Text(appBarTitle),
elevation: 1,
actions: [
IconButton(
icon: Icon(
Icons.search,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => SearchContacts()));
},
),
],
),
body:Form(
key: globalFormKey,
child: Container(
padding: EdgeInsets.only(left: 16, top: 25, right: 16),
child:
GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: ListView(
children: [
ImageProfile(customer.cust_photo),
SizedBox(
height: 35,
),
buildTextField("Name",custfNameController,
(value) => updatefName(value),(value)=>checkfname(value)),
buildTextField("Mobile",custMobileNoController,
(value) => updateMobile(value),(value)=>checkmobile(value)),
buildTextField("Company",custCompanyController,
(value) => updateCompany(value),(value)=>checkempty(value)),
buildTextField("Email",custEmailController,
(value) => updateEmail(value),(value)=>checkmail(value)),
Text("Address"),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: addrController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,//Normal textInputField will be displayed
maxLines: 5, // when user presses enter it will adapt to it
onChanged: (value) {
this.customer.addr = value;
},
),
),
SizedBox(
height: height * 0.02,
),
Divider(),
SizedBox(
height: height * 0.02,
),
Row(
children: <Widget>[
Expanded(
child: Text("Show on Call",
style: textStyle,
)
),
SizedBox(
height: height * 0.02,
),
SizedBox(
height: 35,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
OutlineButton(
padding: EdgeInsets.symmetric(horizontal: 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
onPressed: () {},
child: Text("CANCEL",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.black)),
),
RaisedButton(
onPressed: () {
setState(() {
_saveCustomer();
});
},
//color: Colors.purpleAccent,
color: Theme.of(context).primaryColor,
padding: EdgeInsets.symmetric(horizontal: 50),
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Text(
"SAVE",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.white),
),
)
],
)
],
),
),
),
)));
}
Widget bottomSheet(){
return Container(
height: 100,
width: MediaQuery.of(context).size.width ,
margin: EdgeInsets.symmetric(
horizontal:20,
vertical:20,
),
child: Column(
children: <Widget>[
Text("Choose profile photo",
style: TextStyle(fontSize: 20.0),),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton.icon(
onPressed: (){
getImage(ImageSource.camera);
},
icon:Icon(Icons.camera,color: Theme.of(context).primaryColor,), label:Text("camera")),
FlatButton.icon(
onPressed: (){
getImage(ImageSource.gallery);
},
icon:Icon(Icons.photo_library), label:Text("Gallery"))
],
)
],
),
);
}
//This is for 1st 3 Textfields name,mobile,company
Widget buildTextField(String labelText,tController,Function onChanged,Function validator) {
return Padding(
padding: const EdgeInsets.only(bottom: 35.0),
child: TextFormField(
controller:tController,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 3),
labelText: labelText,
labelStyle:TextStyle(),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
onChanged: (String value) {
return onChanged(value);
},
validator:(String value) {
return validator(value);
},
),
);
}
void moveToLastScreen() {
Navigator.pop(context, true);
}
bool validateAndSave() {
final form = globalFormKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
void _saveCustomer() async {
if (validateAndSave()) {
var result;
var res;
var mob = await dbService.checkcustMobno(mobnum,uname);
var mail = await dbService.checkcustEmail(email,uname);
if (mob != null) {
FormHelper.showAlertDialog(
context, 'Error',
'Customer with this mobile number already exists');
}
else if (mail != null) {
FormHelper.showAlertDialog(
context, 'Error',
'Customer with this email id already exists');
}else {
if (customer.cust_id != null) { // Case 1: Update operation
result = await dbService.updateCustomer(customer);
} else { // Case 2: Insert Operation
result = await dbService.insertCustomer(customer);
}
if (result != 0) { // Success
moveToLastScreen();
FormHelper.showAlertDialog(
context, 'Status', 'Customer Saved Successfully');
} else { // Failure
FormHelper.showAlertDialog(
context, 'Status', 'Problem Saving Customer');
}
languages.forEach((lang) async {
print("${lang.name} : ${lang.selected}");
if (lang.selected) {
LanguagesModel language = LanguagesModel(lang: lang.name);
print("customer id from lang");
print(customer.cust_id);
await dbService.insertLanguages(language);
}
});
}
}
}
String updatefName(String value) {
customer.first_name = custfNameController.text;
customer.cre_by=uname;
print(uname);
}
String updatelName(String value) {
if(value.isEmpty)
customer.last_name = " ";
else
customer.last_name = custlNameController.text;
}
String updateMobile(value) {
customer.mob_num = custMobileNoController.text;
mobnum=value;
}
String updateEmail(value) {
customer.email_id = custEmailController.text;
email=value;
}
String updateCompany(String value) {
customer.org_name = custCompanyController.text;
}
String checkfname(String value){
if(value.isEmpty)
{
return "First name can't be null";
}
return null;
}
String checkempty(String value){
print("checkempty called");
if(value.isEmpty)
{
return "Can't be null";
}
return null;
}
String checkmobile(String value) {
print("checkmobile called");
if(value.isEmpty)
{
return 'Please enter phone no.';
}
if(value.length<6)
{
return 'Please enter a valid phone no.';
}
return null;
}
String checkmail(String value){
print("checkmail called");
if(value.isEmpty)
{
return 'Please Enter E-mail address';
}
if (!EmailValidator.validate(value)) {
return 'Please enter a valid Email';
}
return null;
}
}
Replace the ListView (that the buildTextFields are its children) with a Column and wrap the Column with a SingleChildScrollView.

Snackbar appearing repeatedly after appearing once

I have shown snackbar after incorrect login in flutter. But after appearing once, the snackbar is appearing repeatedly without even pressing the submit button. Where am I doing wrong? Please help. Here is my code below. In the snapshot.data.status == '2' portion I have showing the snackbar. I want the snackbar to be displayed only when the login falis i.e. when snapshot.data.status == '2' satisfies.
class MyApp extends StatefulWidget {
final UserDataStorage storage;
MyApp({Key key, #required this.storage}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _TextControl();
}
}
class _TextControl extends State<MyApp> {
final _formKey = GlobalKey<FormState>();
bool snackBarActive = false;
#override
void initState() {
super.initState();
widget.storage.readCounter().then((int value) {
if (value > 0) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TextInput(storage: GetDataStorage())),
);
}
});
}
final TextEditingController _controller = TextEditingController();
final TextEditingController _controller2 = TextEditingController();
#override
void dispose() {
_controller.dispose();
_controller2.dispose();
super.dispose();
}
Future<Login> _futureLogin;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.purple[400],
title: Text('Login'),
),
body: Container(
padding: EdgeInsets.only(left: 15, top: 20, right: 15, bottom: 20),
child: Column(
children: <Widget>[
Center(
child: Image(image: AssetImage('assets/images/logo.png')),
),
Container(
padding: EdgeInsets.only(left: 0, top: 20, right: 0, bottom: 0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
children: <Widget>[
TextFormField(
controller: _controller,
decoration: InputDecoration(hintText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value.isEmpty || !value.isValidEmail()) {
return 'Please enter valid email.';
}
return null;
},
),
TextFormField(
controller: _controller2,
decoration: InputDecoration(hintText: 'Password'),
obscureText: true,
validator: (value) {
if (value.isEmpty) {
return 'Please enter password.';
}
return null;
},
),
Container(
margin: EdgeInsets.only(top: 10.0),
child: RaisedButton(
color: Colors.purple[400],
padding: EdgeInsets.only(
left: 130, top: 10, right: 130, bottom: 10),
textColor: Colors.white,
onPressed: () {
if (_formKey.currentState.validate()) {
setState(() {
_futureLogin = userLogin(
_controller.text, _controller2.text);
});
Scaffold.of(context)
.removeCurrentSnackBar();
}
},
child: Text('Login',
style: TextStyle(fontSize: 18.0)),
),
),
],
),
(_futureLogin != null)
? FutureBuilder<Login>(
future: _futureLogin,
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data.status == '1') {
widget.storage
.writeCounter(snapshot.data.usrid);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TextInput(
storage: GetDataStorage())),
);
} else if (snapshot.data.status == '2') {
snackBarActive = true;
if (snackBarActive) {
Scaffold.of(context)
.showSnackBar(SnackBar(
content: Text(
"Invalid login credentials.",
style: TextStyle(
color: Colors.red[100])),
))
.closed
.whenComplete(() {
setState(() {
snackBarActive = false;
});
});
}
return Text('');
}
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(
child: CircularProgressIndicator());
},
)
: Text(''),
],
)),
),
],
)),
);
}
}
Have you tried changing the status variable to 1 after checking snapshot.data.status == '2', try that and it might help you stop the continuous snackbar widget showing up.
Write this code before calling snackbar,
ScaffoldMessenger.of(context).hideCurrentSnackBar();
example;
getSnackBar(BuildContext context, String snackText) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(snackText)));
}