How to edit a selected item from a list in flutter - flutter

I have been trying to add an edit function to my to do list in which a user can select the item the user wants to edit, then that should pop a dialog where there is a textfield to enter the new value of the selected item and a Button that saves the changes. Currently I have a function that calls the array where the tasks are stored then it is supposed to triger the selected item using index so that at the end that selected value could be given a new value when onPressed, see this edit functionality as instagrams one except it edits text.
The problem comes when calling that function into the dialog's edit button because I am doing it like this onPressed: () => _editToDoItem(_controller.text, index) and since I have to pass 2 parameters there, the error I am getting is Undefined name 'index'. How can this problem be solved to make this edit function work?. By the way, I haven't get to try the edit function because of this error so please correct me if the function or any part of the code is incorrect.
everything to do with the edit function below.
List<ToDoElement> _toDoItems = [];
TextEditingController _controller = TextEditingController();
// this function adds a task to the list
void _addToDoItem(String task) {
if(task.isNotEmpty) {
setState(() {
_toDoItems.add(ToDoElement(task, DateTime.now()));
});
}
}
// this is the function that is supposed to edit the selected index from the _toDoItems array
void _editToDoItem(String newText, int index) {
setState(() {
_toDoItems[index].task = newText;
});
}
_editDialog(BuildContext context) {
return showDialog(context: context, builder: (context) {
return Dialog(
child: Container(
height: 180,
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 60,
child: TextField(
controller: _controller,
autofocus: true,
style: TextStyle(fontSize: 18,),
)
),
Container(
height: 65,
width: double.infinity,
margin: EdgeInsets.only(top: 5,),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('EDIT'),
onPressed: () {
_editToDoItem(_controller.text, index); // error on index, Undefined name 'index'
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
],
),
),
);
});
}
full main.dart file
class ToDoElement {
String task;
final DateTime timeOfCreation;
ToDoElement(this.task, this.timeOfCreation);
}
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<ToDoElement> _toDoItems = [];
TextEditingController _controller = TextEditingController();
void _addToDoItem(String task) {
if(task.isNotEmpty) {
setState(() {
_toDoItems.add(ToDoElement(task, DateTime.now()));
});
}
}
void _editToDoItem(String newText, int index) {
setState(() {
_toDoItems[index].task = newText;
});
}
void _removeTodoItem(int index) {
setState(() => _toDoItems.removeAt(index));
}
_editDialog(BuildContext context) {
return showDialog(context: context, builder: (context) {
return Dialog(
backgroundColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
padding: EdgeInsets.all(20),
height: 180,
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 60,
child: TextField(
controller: _controller,
autofocus: true,
/*onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},*/
style: TextStyle(fontSize: 18,),
decoration: InputDecoration(
hintText: 'Add a task here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
)
),
Container(
height: 65,
width: double.infinity,
margin: EdgeInsets.only(top: 5,),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('EDIT', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_editToDoItem(_controller.text, index);
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
],
),
),
);
});
}
Widget _buildToDoItem(String toDoText, int index) {
return SizedBox(
child: Container(
height: 58,
margin: EdgeInsets.only(left: 22.0, right: 22.0, bottom: 12,),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: Colors.red),
borderRadius: BorderRadius.all(Radius.circular(18)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children:[
Expanded(
child: ListTile(
title: Text(
toDoText,
style: TextStyle(fontSize: 18),
),
onTap: () => null,
),
),
FlatButton(
child: Text('Edit', style: TextStyle(color: Colors.red, fontSize: 16.5),),
onPressed: () => _editDialog(context),
),
FlatButton(
child: Text('Delete', style: TextStyle(color: Colors.red, fontSize: 16.5),),
onPressed: () => _removeTodoItem(index),
),
],
),
),
);
}
int compareElement(ToDoElement a, ToDoElement b) =>
a.timeOfCreation.isAfter(b.timeOfCreation) ? -1 : 1;
Widget _buildToDoList() {
_toDoItems.sort(compareElement);
return Expanded(
child: ListView.builder(
itemCount: _toDoItems.length,
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index].task, index);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text('To Do List', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold,),),
)
),
backgroundColor: Colors.white,
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 60,
margin: EdgeInsets.all(22),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Container(
height: double.infinity,
child: TextField(
controller: _controller,
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},
style: TextStyle(fontSize: 18,),
decoration: InputDecoration(
hintText: 'Add a task here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
),
),
),
Expanded(
flex: 4,
child: Container(
height: double.infinity,
margin: EdgeInsets.only(left: 12),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('ADD', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_addToDoItem(_controller.text);
_controller.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
),
],
),
),
_buildToDoList()
]
),
),
);
}
}
If you have any questions please let me know in the comments;)

You can copy paste run full code below
You can provide index to _editDialog then _editToDoItem can get index
code snippet
_editDialog(BuildContext context, int index)
...
FlatButton(
child: Text(
'Edit',
style: TextStyle(color: Colors.red, fontSize: 16.5),
),
onPressed: () => _editDialog(context, index),
),
working demo
full code
import 'package:flutter/material.dart';
class ToDoElement {
String task;
final DateTime timeOfCreation;
ToDoElement(this.task, this.timeOfCreation);
}
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<ToDoElement> _toDoItems = [];
TextEditingController _controller = TextEditingController();
TextEditingController _controller1 = TextEditingController();
void _addToDoItem(String task) {
if (task.isNotEmpty) {
setState(() {
_toDoItems.add(ToDoElement(task, DateTime.now()));
});
}
}
void _editToDoItem(String newText, int index) {
setState(() {
_toDoItems[index].task = newText;
});
}
void _removeTodoItem(int index) {
setState(() => _toDoItems.removeAt(index));
}
_editDialog(BuildContext context, int index) {
return showDialog(
context: context,
builder: (context) {
return Dialog(
backgroundColor: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
padding: EdgeInsets.all(20),
height: 180,
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 60,
child: TextField(
controller: _controller,
autofocus: true,
/*onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},*/
style: TextStyle(
fontSize: 18,
),
decoration: InputDecoration(
hintText: 'Add a task here...',
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
)),
Container(
height: 65,
width: double.infinity,
margin: EdgeInsets.only(
top: 5,
),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('EDIT', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_editToDoItem(_controller.text, index);
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
],
),
),
);
});
}
Widget _buildToDoItem(String toDoText, int index) {
return SizedBox(
child: Container(
height: 58,
margin: EdgeInsets.only(
left: 22.0,
right: 22.0,
bottom: 12,
),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: Colors.red),
borderRadius: BorderRadius.all(Radius.circular(18)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: ListTile(
title: Text(
toDoText,
style: TextStyle(fontSize: 18),
),
onTap: () => null,
),
),
FlatButton(
child: Text(
'Edit',
style: TextStyle(color: Colors.red, fontSize: 16.5),
),
onPressed: () => _editDialog(context, index),
),
FlatButton(
child: Text(
'Delete',
style: TextStyle(color: Colors.red, fontSize: 16.5),
),
onPressed: () => _removeTodoItem(index),
),
],
),
),
);
}
int compareElement(ToDoElement a, ToDoElement b) =>
a.timeOfCreation.isAfter(b.timeOfCreation) ? -1 : 1;
Widget _buildToDoList() {
_toDoItems.sort(compareElement);
return Expanded(
child: ListView.builder(
itemCount: _toDoItems.length,
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index].task, index);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text(
'To Do List',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
)),
backgroundColor: Colors.white,
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
Container(
height: 60,
margin: EdgeInsets.all(22),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Container(
height: double.infinity,
child: TextField(
controller: _controller1,
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
_controller1.clear();
},
style: TextStyle(
fontSize: 18,
),
decoration: InputDecoration(
hintText: 'Add a task here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
),
),
),
Expanded(
flex: 4,
child: Container(
height: double.infinity,
margin: EdgeInsets.only(left: 12),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('ADD', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_addToDoItem(_controller1.text);
_controller1.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
),
],
),
),
_buildToDoList()
]),
),
);
}
}

Related

Alert Dialog not working as expected in flutter

I was trying to show 2 dialog same time and when i open second dialog, its not focusing on the widget that was in second dialog, its focusing on the widget thats on first dialog that i have opened before.
Is this issue or am i not supposed to open 2 dialog at same time?
Here is video to the issue
Here is first dialog code
showDialog(
context: context,
builder: (_) =>
AlertDialog(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
width: 16,
height: 32,
decoration: BoxDecoration(
color: AppColors.colorFFBC99,
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(
width: 16,
),
Text(
S.addaRecipe,
style: Theme.of(context).textTheme.headlineSmall!.copyWith(
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
],
),
SizedBox(
width: 300,
child: Row(
children: [
Text(
S.recipeBy,
style: Theme.of(context)
.textTheme
.labelLarge!
.copyWith(fontWeight: FontWeight.w500),
),
SizedBox(
width: 8,
),
Expanded(
child: CustomMyDropDownButton(label: 'dsfsdsf'),
),
],
),
)
],
),
content: Form(
// key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(
height: 16,
),
Text(
S.addPhotos,
style: Theme.of(context)
.textTheme
.labelLarge!
.copyWith(fontWeight: FontWeight.w500),
),
const SizedBox(
height: 8,
),
Container(
width: double.infinity,
// height: 200,
color: Colors.white,
child: Wrap(
children: [
for (int i = 0; i < 10; i++)
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 200,
height: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.network(
S.recipeNetworkImage,
fit: BoxFit.cover,
),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {},
child: Container(
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(8),
),
width: 200,
height: 200,
child: const Center(
child: Icon(
Icons.add,
size: 32,
),
),
),
),
),
],
),
),
const SizedBox(
height: 16,
),
CustomTextField(
showLabel: true,
// controller: textEditingController,
label: S.recipeName,
validator: (v) {
if (v!.isEmpty) {
return 'This field is required';
}
return null;
},
),
const SizedBox(
height: 16,
),
CustomTextField(
showLabel: true,
// controller: textEditingController,
label: S.description,
validator: (v) {
if (v!.isEmpty) {
return 'This field is required';
}
return null;
},
),
const SizedBox(
height: 32,
),
Row(
children: [
Text(
S.nutritionalInfo,
style: Theme.of(context)
.textTheme
.labelLarge!
.copyWith(fontWeight: FontWeight.w500),
),
IconButton(
onPressed: () {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text(
S.addNutrition,
),
content: Column(
mainAxisSize: MainAxisSize.min,
children: const [
CustomTextField(
showLabel: true,
label: S.name,
),
CustomTextField(
showLabel: true,
label: S.value,
),
],
),
actions: [
CustomOutlinedButton(
name: S.close,
onPress: () {
context.pop();
}),
CustomElevatedButton(
name: S.add,
onPress: () {},
),
],
),
);
},
icon: const Icon(Icons.add),
)
],
),
const SizedBox(
height: 8,
),
Container(
padding: EdgeInsets.all(8),
color: Colors.grey.shade100,
child: 1 == 1
? Text(
"Nutrition Info....",
)
: Column(
children: [
for (int i = 0; i < 0; i++)
ListTile(
leading:
Icon(Icons.horizontal_split_rounded),
title: Text('Calories'),
subtitle: Text('237'),
trailing: IconButton(
onPressed: () {},
icon: Icon(Icons.delete),
),
),
],
),
),
const SizedBox(
height: 32,
),
Text(
S.steps,
style: Theme.of(context)
.textTheme
.labelLarge!
.copyWith(fontWeight: FontWeight.w500),
),
const SizedBox(
height: 8,
),
Container(
color: AppColors.colorF4F4F4,
height: 300,
width: MediaQuery.of(context).size.width * .8,
child: HtmlEditor(
controller: HtmlEditorController(),
htmlEditorOptions: const HtmlEditorOptions(
hint: "Steps....",
),
otherOptions: const OtherOptions(
height: 400,
decoration: BoxDecoration(color: Colors.red)),
),
),
const SizedBox(
height: 32,
),
],
),
),
),
const SizedBox(
height: 32,
),
Stack(
children: [
Text(
'',
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Colors.red,
),
),
Text(
'',
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Colors.green,
),
),
],
),
],
),
),
actions: [
CustomOutlinedButton(
name: S.close,
onPress: () {
context.pop();
}),
CustomElevatedButton(
name: S.add,
onPress: () {},
),
],
);
Here is the code of second dialog show dialog
showDialog(
context: context,
builder: (_) => AlertDialog(
title: const Text(
S.addNutrition,
),
content: Column(
mainAxisSize: MainAxisSize.min,
children: const [
CustomTextField(
showLabel: true,
label: S.name,
),
CustomTextField(
showLabel: true,
label: S.value,
),
],
),
actions: [
CustomOutlinedButton(
name: S.close,
onPress: () {
context.pop();
}),
CustomElevatedButton(
name: S.add,
onPress: () {},
),
],
),
);
Here is customtextfield code
import 'package:flutter/material.dart';
class CustomTextField extends StatefulWidget {
final String? label;
final TextEditingController? controller;
final String? Function(String?)? validator;
final Function(String?)? onSaved;
final bool showLabel;
final bool enableSuggestions;
final bool autocorrect;
final TextInputType? keyBoardType;
final Function(String)? onChange;
final bool showSuffixIcon;
const CustomTextField({
Key? key,
this.label,
this.controller,
this.validator,
this.onSaved,
this.enableSuggestions = true,
this.autocorrect = true,
this.keyBoardType,
this.onChange,
this.showSuffixIcon = false,
this.showLabel = false,
}) : super(key: key);
#override
State<CustomTextField> createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
final textFieldFocusNode = FocusNode();
bool _obscured = false;
#override
void initState() {
// TODO: implement initState
if (widget.showSuffixIcon) {
_obscured = true;
}
super.initState();
}
void _toggleObscured() {
setState(() {
_obscured = !_obscured;
if (textFieldFocusNode.hasPrimaryFocus)
return; // If focus is on text field, dont unfocus
textFieldFocusNode.canRequestFocus =
false; // Prevents focus if tap on eye
});
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
widget.showLabel
? Text(
widget.label!,
style: Theme.of(context)
.textTheme
.labelLarge!
.copyWith(fontWeight: FontWeight.w500),
)
: const SizedBox(),
SizedBox(
height: widget.showLabel ? 8 : 0,
),
TextFormField(
controller: widget.controller,
validator: widget.validator,
onSaved: widget.onSaved,
onChanged: widget.onChange,
focusNode: textFieldFocusNode,
obscureText: _obscured,
enableSuggestions: widget.enableSuggestions,
autocorrect: widget.autocorrect,
keyboardType: widget.keyBoardType,
decoration: InputDecoration(
isDense: true,
enabledBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
borderSide: BorderSide(
color: Colors.black12,
),
),
focusedBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
borderSide: BorderSide(
color: Colors.black12,
),
),
errorBorder: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
borderSide: BorderSide(
color: Colors.red,
),
),
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
borderSide: BorderSide(
color: Colors.black12,
),
),
labelText: widget.showLabel ? null : widget.label,
// labelStyle: CustomTextStyle.kTextStyle16400.copyWith(
// color: AppColors.textColor2,
// ),
suffixIcon: widget.showSuffixIcon
? Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 4, 0),
child: GestureDetector(
onTap: _toggleObscured,
child: Icon(
_obscured
? Icons.visibility_rounded
: Icons.visibility_off_rounded,
size: 24,
color: Colors.grey,
),
),
)
: null,
),
),
],
);
}
}
Try to add autofocus: true, on your CustomTextField. It should do handle rest I believe.
TextField(
autofocus: true,
);

How to make container fixed. the container wont resize after clicking the widgets inside it . Flutter

I am having trouble with my design as i want this container as a background for my dropdowns and textformfield. but its changing its size once i click on description or dates.
Please help how to make it fixed. i have attached some screenshots also of before and after clicking the formfield.
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
// color: Colors.white,
padding: const EdgeInsets.all(32.5),
constraints: const BoxConstraints(
minWidth: 0, maxWidth: 350, minHeight: 0, maxHeight: 440),
child: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 52,
width: 270,
padding: const EdgeInsets.symmetric(horizontal: 5.0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text('Select Chapter'),
items: chapteritemlist.map((item) {
return DropdownMenuItem(
value: item['chapterId'].toString(),
child: Text(item['chapter'].toString()),
);
}).toList(),
onChanged: (newVal) {
setState(() {
dropdownchapterdisplay = newVal;
});
chaptid = newVal;
print(chaptid);
getAllMember();
},
value: dropdownchapterdisplay,
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 52,
width: 270,
padding: EdgeInsets.symmetric(horizontal: 0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text('Select Member'),
items: memberitemlist.map((item) {
return DropdownMenuItem(
value: item['id'].toString(),
child: Text(
item['name'].toString(),
style: const TextStyle(
fontSize: 9,
),
),
);
}).toList(),
onChanged: (newVal) {
setState(() {
dropdownmemberdisplay = newVal;
});
memberid = newVal;
},
value: dropdownmemberdisplay,
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: SizedBox(
height: 48,
width: 270,
child: TextFormField(
// The validator receives the text that the user has entered.
// textAlign: TextAlign.center,
controller: description,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintText: "Description",
filled: true,
fillColor: Colors.grey[200],
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: SizedBox(
height: 88,
width: 270,
child: DateTimeFormField(
decoration: InputDecoration(
hintStyle: const TextStyle(color: Colors.black),
errorStyle: const TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintText: 'MM DD, YYYY',
filled: true,
fillColor: Colors.grey[200],
suffixIcon: const Icon(Icons.event_note),
labelText: 'Select Date',
),
mode: DateTimeFieldPickerMode.date,
autovalidateMode: AutovalidateMode.always,
validator: (e) => (e?.day ?? 0) == 1
? 'Please not the first day'
: null,
onDateSelected: (DateTime value) {},
),
),
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(children: <Widget>[
Padding(
padding: const EdgeInsets.all(6.0),
child: Align(
alignment: Alignment.bottomLeft,
child: ElevatedButton(
onPressed: () {
saveRequestModel = SaveClass();
saveRequestModel.Description = description.text;
saveRequestModel.UserName = global_Email;
saveRequestModel.Id = 0;
saveRequestModel.toFId = 0;
saveRequestModel.ToSelf = 0;
saveRequestModel.TranType = 0;
saveRequestModel.ToId = 6;
saveRequestModel.MeetingDate = '2022-10-02';
print(saveRequestModel.ToId);
SaveService saveService = SaveService();
saveService.save(saveRequestModel).then((value) {
print("data saved");
});
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple[900],
textStyle: const TextStyle(
color: Colors.white,
fontSize: 25,
fontStyle: FontStyle.normal),
),
// color: Colors.deepPurple[900],
// textColor: Colors.white,
// elevation: 5,
child: const Text('Save',
style: TextStyle(fontSize: 20)),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: Align(
alignment: Alignment.bottomRight,
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple[900],
textStyle: const TextStyle(
color: Colors.white,
fontSize: 25,
fontStyle: FontStyle.normal),
),
// color: Colors.deepPurple[900],
// textColor: Colors.white,
// elevation: 5,
child: const Text('Check Report',
style: TextStyle(fontSize: 20)),
),
))
]),
),
],
)),
Here is the full code.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:date_field/date_field.dart';
//import 'package:saarthi/api/saarthi_meeting/chapter_api.dart';
import 'package:saarthi/api/saarthi_meeting/sarthi_services.dart';
import 'package:http/http.dart' as http;
import 'package:saarthi/api/saarthi_meeting/save_button.dart';
import 'package:saarthi/model/saarthi_meeting/saarthi_model.dart';
import 'package:saarthi/model/saarthi_meeting/save_model.dart';
import 'package:saarthi/variables.dart';
void main() {
runApp(Saarthi_Meeting());
}
class Saarthi_Meeting extends StatelessWidget {
Saarthi_Meeting({Key? key}) : super(key: key);
String value = "";
String url = '';
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: datadisplay(),
debugShowCheckedModeBanner: false,
);
}
}
class datadisplay extends StatefulWidget {
const datadisplay({Key? key}) : super(key: key);
#override
State<datadisplay> createState() => _datadisplayState();
}
class _datadisplayState extends State<datadisplay> {
final SaarthiService _fetchdata = SaarthiService();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.deepPurple[900],
appBar: AppBar(
title: Image.asset('assets/images/CG.png', width: 200),
backgroundColor: Colors.deepPurple[900],
elevation: 13,
actions: [
IconButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => smdesign()));
},
icon: const Icon(Icons.add),
)
],
),
body: Container(
padding: const EdgeInsets.all(20),
child: FutureBuilder<List<Saarthidata>>(
future: _fetchdata.smdata(),
builder: (context, snapshot) {
var data = snapshot.data;
return ListView.builder(
itemCount: data?.length,
itemBuilder: (context, index) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
onTap: () {
if (data?[index].id != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => smdesign(),
),
);
}
},
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'On Date - ${data?[index].date}',
style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600),
),
const SizedBox(height: 10),
Text(
'From User - ${data?[index].fromName}',
style: const TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 10),
Text(
'To User - ${data?[index].toName}',
style: const TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 10),
]),
),
),
);
});
}),
),
);
}
}
class smdesign extends StatefulWidget {
smdesign({Key? key}) : super(key: key);
#override
State<smdesign> createState() => _smdesignState();
}
class _smdesignState extends State<smdesign> {
String? dropdownvalue = "Self";
String chaptervalue = "One";
bool isVisible = false;
//---------------------variable----------------------------------------------------API
List chapteritemlist = [];
var dropdownchapterdisplay;
//---------------------variable----------------------------------------------------API
List memberitemlist = [];
var dropdownmemberdisplay;
//------------------------------api dropdown 3 ---------------------------------
//--------------------------------------------------------------------------API
//----------------------------------save-------------------save--------------------------
late SaveClass saveRequestModel;
var description = TextEditingController();
//----------------------------------save-------------------save--------------------------
#override
void initState() {
super.initState();
getAllChapter();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.deepPurple[900],
appBar: AppBar(
title: Image.asset('assets/images/CG.png', width: 200),
backgroundColor: Colors.deepPurple[900],
elevation: 13,
),
body: Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
// color: Colors.white,
padding: const EdgeInsets.all(32.5),
constraints: const BoxConstraints(
minWidth: 0, maxWidth: 350, minHeight: 0, maxHeight: 440),
child: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 52,
width: 270,
padding: const EdgeInsets.symmetric(horizontal: 5.0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text('Select Chapter'),
items: chapteritemlist.map((item) {
return DropdownMenuItem(
value: item['chapterId'].toString(),
child: Text(item['chapter'].toString()),
);
}).toList(),
onChanged: (newVal) {
setState(() {
dropdownchapterdisplay = newVal;
});
chaptid = newVal;
print(chaptid);
getAllMember();
},
value: dropdownchapterdisplay,
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 52,
width: 270,
padding: EdgeInsets.symmetric(horizontal: 0),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
// color: Colors.black,
style: BorderStyle.solid,
width: 1.0),
),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text('Select Member'),
items: memberitemlist.map((item) {
return DropdownMenuItem(
value: item['id'].toString(),
child: Text(
item['name'].toString(),
style: const TextStyle(
fontSize: 9,
),
),
);
}).toList(),
onChanged: (newVal) {
setState(() {
dropdownmemberdisplay = newVal;
});
memberid = newVal;
},
value: dropdownmemberdisplay,
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: SizedBox(
height: 48,
width: 270,
child: TextFormField(
// The validator receives the text that the user has entered.
// textAlign: TextAlign.center,
controller: description,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintText: "Description",
filled: true,
fillColor: Colors.grey[200],
),
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: SizedBox(
height: 88,
width: 270,
child: DateTimeFormField(
decoration: InputDecoration(
hintStyle: const TextStyle(color: Colors.black),
errorStyle: const TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintText: 'MM DD, YYYY',
filled: true,
fillColor: Colors.grey[200],
suffixIcon: const Icon(Icons.event_note),
labelText: 'Select Date',
),
mode: DateTimeFieldPickerMode.date,
autovalidateMode: AutovalidateMode.always,
validator: (e) => (e?.day ?? 0) == 1
? 'Please not the first day'
: null,
onDateSelected: (DateTime value) {},
),
),
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(children: <Widget>[
Padding(
padding: const EdgeInsets.all(6.0),
child: Align(
alignment: Alignment.bottomLeft,
child: ElevatedButton(
onPressed: () {
saveRequestModel = SaveClass();
saveRequestModel.Description = description.text;
saveRequestModel.UserName = global_Email;
saveRequestModel.Id = 0;
saveRequestModel.toFId = 0;
saveRequestModel.ToSelf = 0;
saveRequestModel.TranType = 0;
saveRequestModel.ToId = 6;
saveRequestModel.MeetingDate = '2022-10-02';
print(saveRequestModel.ToId);
SaveService saveService = SaveService();
saveService.save(saveRequestModel).then((value) {
print("data saved");
});
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple[900],
textStyle: const TextStyle(
color: Colors.white,
fontSize: 25,
fontStyle: FontStyle.normal),
),
// color: Colors.deepPurple[900],
// textColor: Colors.white,
// elevation: 5,
child: const Text('Save',
style: TextStyle(fontSize: 20)),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: Align(
alignment: Alignment.bottomRight,
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple[900],
textStyle: const TextStyle(
color: Colors.white,
font size: 25,
fontStyle: FontStyle.normal),
),
// color: Colors.deepPurple[900],
// textColor: Colors.white,
// elevation: 5,
child: const Text('Check Report',
style: TextStyle(fontSize: 20)),
),
))
]),
),
],
)),
),
);
}
}
Before Image -This is before clicking anything. The design
After Image -when I click on the description form field it shows like this.

How to show an alert dialog after the user click the button in flutter

I'm new in flutter and I'm trying to show a dialog alert for the result if the user click on "Calculate" button. I want to change the "Text" result into the dialog alert like "The prediction of (total days) is (result)" Anyone can help me how to do this? I can't find any suitable resource for this, Thank you
class TransactionYearly extends StatefulWidget {
#override
_TransactionYearlyState createState() => _TransactionYearlyState();
}
class _TransactionYearlyState extends State<TransactionYearly> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController amount = new TextEditingController();
final TextEditingController day = new TextEditingController();
double _result;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(getTranslated(context, 'prediction_calculation'),),
elevation: 0,
brightness: Brightness.light,
backgroundColor: primary,
leading: IconButton(
onPressed: (){
Navigator.pop(context, MaterialPageRoute(builder: (context) => Transactions()));
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 300,
child: Image(
image: AssetImage("assets/girlsave.png"),
fit: BoxFit.contain,
),
),
Container(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Please fill up the text fields';
},
controller: amount,
decoration: InputDecoration(
labelText: getTranslated(context, 'amount_text'),
labelStyle: TextStyle(color: Colors.grey),
prefixIcon: Icon(
Icons.attach_money,
color: secondary,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
keyboardType: TextInputType.number,
),
),
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty)
return 'Please fill up the text fields';
},
controller: day,
decoration: InputDecoration(
labelText: getTranslated(context, 'day_text'),
labelStyle: TextStyle(color: Colors.grey),
prefixIcon: Icon(
Icons.date_range_outlined,
color: secondary,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: secondary),
),
),
keyboardType: TextInputType.number,
),
),
SizedBox(height: 20),
Container(
padding: EdgeInsets.only(
top: 25.0, left: 20.0, right: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget> [
Expanded (
child: ElevatedButton(
onPressed: () {
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
calculate();
},
child: Text(getTranslated((context), "calculate_button").toUpperCase(), style: TextStyle (
fontSize: 14,
)),
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(15)),
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
side: BorderSide(color: secondary)
),
),
),
),
),
SizedBox(width: 20, height: 10),
Expanded(
child: ElevatedButton(
onPressed: () {
amount.clear();
day.clear();
},
child: Text(getTranslated((context), "clear_button").toUpperCase(), style: TextStyle (
fontSize: 14
)),
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(15)),
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
side: BorderSide(color: secondary)
),
),
),
),
)
],
)
),
Text(
_result == null ? "Enter amount" : "$_result",
)
],
),
),
),
],
),
),
));
}
void calculate(){
double amounts = double.parse(amount.text);
double days = double.parse(day.text);
double result = amounts * days;
_result = result;
setState(() {
});
}
}
After calculate call you can show dialog like this in the onPressed function.
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Result'),
content: Text('Result is $_result'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go Back'))
],
),
);

Flutter TextField hide by Keyboard

I'm a beginner in the flutter, I have a conflict, when I'm focusing on a TexFiled, the keyboard hidden over the TextField, and bottom button not showing i attached my conflict here
any solution for this
Thanks
code here
import 'dart:ui';
import 'package:crapp/pages/create_password/password_screen.dart';
import 'package:crapp/widgets/components/alert.dart';
import 'package:crapp/widgets/components/page_animation.dart';
import 'package:crapp/widgets/theme/constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:crapp/provider/theme_provider.dart';
class PasswordScreen extends StatefulWidget {
#override
_PasswordScreenState createState() => _PasswordScreenState();
}
class _PasswordScreenState extends State< PasswordScreen > {
final _controller = TextEditingController();
//validation controller
TextEditingController sQuastionController = new TextEditingController();
TextEditingController answerQController = new TextEditingController();
TextEditingController passController = new TextEditingController();
TextEditingController conPassController = new TextEditingController();
final TextEditingController _pass = TextEditingController();
final TextEditingController _confirmPass = TextEditingController();
bool _isButtonEnabled = false;
//final _controller = TextEditingController();
bool isConfirm=false;
check (BuildContext context){
if(sQuastionController.text.isNotEmpty &&
answerQController.text.isNotEmpty &&
conPassController.text.isNotEmpty &&
passController.text.isNotEmpty){
setState(() {
_isButtonEnabled = true;
});
} else {
setState(() {
_isButtonEnabled = false;
});
}
}
checks (BuildContext context){
if(passController.text.isEmpty){
showDialog<void>(
context: context,
builder: (BuildContext dialogContext) {
return Alert(title: "Alert !!!",subTile: "Password must be 10 characters !",);
}
);
}else if(passController.text.length > 0 && passController.text.length < 10){
isConfirm = true;
showDialog<void>(
context: context,
builder: (BuildContext dialogContext) {
return Alert(title: "Alert !!!",subTile: "Password doesn't match !",);
}
);
}
}
checkChanged(){
if( secretVal != null
)
{
setState(() {
isSave = true;
});
}else{
isSave =false;
}
} bool isSave=false;
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
/* double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;*/
Provider.of<ThemeProvider>(context).themeMode == ThemeMode.dark
? 'DarkTheme'
: 'LightTheme';
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: _signUp(),
),
],
),
), bottomNavigationBar: BottomAppBar(
elevation: 4,
child: Container(
height: 70,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(
child: MaterialButton(
height: 44,
onPressed: () {
FocusScope.of(context).requestFocus(FocusNode());
//check();
},
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(4)),
color: Color(0xFF2A3476),
elevation: 0,
highlightElevation: 0,
child: Container(
child: Text(
"Save",
style: TextStyle(
color: Color(0xFF2A3476),
fontSize: 15,
fontFamily: 'medium'),
),
),
),
),
],
),
),
),
),
/* bottomNavigationBar: Container(
padding: EdgeInsets.all(25.0),
decoration: BoxDecoration(color: Colors.white,
),
child: Row(
children: [
Expanded(
child: MaterialButton(
height: 44,
onPressed: () {
FocusScope.of(context).requestFocus(FocusNode());
*//* Navigator.push(context, SlidePageRoute(page:PasswordScreen()));*//*
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
color: _isButtonEnabled ? Color(0xFF2A3476) : Color(0x201E1E99),
elevation: 0,
highlightElevation: 0,
child: Container(
child: Text(
"Next",
style: TextStyle(color: m_fillColor,fontSize: 18,fontWeight: FontWeight.w600 ,
fontFamily: "regular",),
),
),
),
),
],
),
)*/
);
}
Widget _signUp() {
return Container(
constraints: BoxConstraints.expand(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF2A3476),
Color(0xFF2A3476),
],
begin: Alignment.topLeft,
end: Alignment.centerRight,
),
),
child: Form(
key: formKey,
child: Container(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding:
const EdgeInsets.symmetric(vertical: 36.0, horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Create Password",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,fontFamily: "medium",
fontWeight: FontWeight.w800,
),
),
],
),
),
Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Steps to set your",
style: TextStyle(
fontSize: 22,
fontFamily: "regular",
fontWeight: FontWeight.w300,
color: Colors.black,
),
),
Text(
"password",
style: TextStyle(
fontSize: 22,
fontFamily: "regular",
fontWeight: FontWeight.w300,
color: Colors.black,
),
),
SizedBox(
height: 20.0,
), Text(
'Secret Question',
style:
TextStyle( fontSize: 15,
fontFamily: "regular",),
), SizedBox(
height: 8.0,
),
Row(
children: [
Expanded(child: InkWell(
onTap: (){
FocusScope.of(context).requestFocus(FocusNode());
secretDialogue();
},
child: Stack(
children: <Widget>[
TextField(
/* textInputAction: TextInputAction.next,*/
controller: sQuastionController,
enabled: false,
onChanged: (val) {
check(context);
},
decoration: InputDecoration(
labelText: secretVal==null?"Select One":secretVal,
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "",
/* prefixIcon: Icon(
Icons.people_outline_rounded,
color: Colors.grey[600],
)*/
),
),
Positioned.directional(
textDirection: Directionality.of(context),
end: 0,
top: 0,
bottom: 0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child:Image.asset(
"assets/icons/ic_drop_arrow.png",
scale: 9,
)),
)
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Text(
'Answer',
style:
TextStyle( fontSize: 15,
fontFamily: "regular",),
),
SizedBox(
height: 8.0,
),
TextField(
/* keyboardType: TextInputType.emailAddress,*/
/* textInputAction: TextInputAction.next,*/
controller: answerQController,
onChanged: (val){
check(context);
},
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "",
/*prefixIcon: Icon(
Icons.people_outline_rounded,
color: Color(0xFFE1E8F7),
)*/),
),
SizedBox(
height: 20.0,
),
Text(
'Password',
style:
TextStyle( fontSize: 15,
fontFamily: "regular",),
),
SizedBox(
height: 8.0,
),
TextFormField(
/* keyboardType: TextInputType.emailAddress,*/
/* textInputAction: TextInputAction.next,*/
controller: passController,
onChanged: (val){
check(context);
},
//password validation
/* validator: (val){
if(val!.isEmpty)
return 'Empty';
return null;
},*/
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "************",
),
),
SizedBox(
height: 20.0,
),
Text(
'Confirm Password',
style:
TextStyle( fontSize: 15,
fontFamily: "regular",),
),
SizedBox(
height: 8.0,
),
TextFormField(
textInputAction: TextInputAction.done,
controller: conPassController,
onChanged: (val){
check(context);
},
//password validation
/* validator: (val){
if(val!.isEmpty)
return 'Empty';
if(val != _pass.text)
return 'Not Match';
return null;
},*/
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "************",
),
),
SizedBox(
height: 20.0,
),
SizedBox(
height: 8.0,
),
SizedBox(
height:200.0,
),
],
),
),
),
],
),
),
),
),
);
}
//
//Secret Qu Alert
List secretList =[
"-What’s your favorite team?",
"-What’s your astrological sign?",
"-What’s your favorite movie?",
"-What city were you born in?",
"-What was your first car?",
];
var secretVal;
void secretDialogue(){
showDialog<void>(
context: context,
// false = user must tap button, true = tap outside dialog
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context,setState){
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
insetPadding: EdgeInsets.all(20),
child: Container(
padding: EdgeInsets.symmetric(vertical: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(secretList.length, (index){
return InkWell(
onTap: (){
setState(() {
secretVal = secretList[index];
Navigator.pop(context);
});
},
child: Container(
height: 50,
padding: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.centerLeft,
child: Text(secretList[index],
style: TextStyle(
fontSize: 18,
fontFamily: "medium",
),),
),
);
})
),
),
);
}
);
},
);
}
}
Wrap your Column by SingleChildScrollView. It will solve your problem.
like this..
body: SafeArea(
child: SingleChildScrollView(
child: Column(
Also I think after this there is no need of
resizeToAvoidBottomInset: false,
in Scaffold.
Please check out and I have found some inconsistency in code, refactored some of them
import 'dart:ui';
import 'package:crapp/pages/create_password/password_screen.dart';
import 'package:crapp/widgets/components/alert.dart';
import 'package:crapp/widgets/components/page_animation.dart';
import 'package:crapp/widgets/theme/constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:crapp/provider/theme_provider.dart';
class PasswordScreen extends StatefulWidget {
#override
_PasswordScreenState createState() => _PasswordScreenState();
}
class _PasswordScreenState extends State< PasswordScreen > {
final _controller = TextEditingController();
//validation controller
TextEditingController sQuastionController = new TextEditingController();
TextEditingController answerQController = new TextEditingController();
TextEditingController passController = new TextEditingController();
TextEditingController conPassController = new TextEditingController();
final TextEditingController _pass = TextEditingController();
final TextEditingController _confirmPass = TextEditingController();
bool _isButtonEnabled = false;
//final _controller = TextEditingController();
bool isConfirm = false;
check(BuildContext context) {
if (sQuastionController.text.isNotEmpty &&
answerQController.text.isNotEmpty &&
conPassController.text.isNotEmpty &&
passController.text.isNotEmpty) {
setState(() {
_isButtonEnabled = true;
});
} else {
setState(() {
_isButtonEnabled = false;
});
}
}
void initState() {
SystemChannels.textInput.invokeMethod('TextInput.hide');
super.initState();
}
checks (BuildContext context){
if(passController.text.isEmpty){
showDialog<void>(
context: context,
builder: (BuildContext dialogContext) {
return Alert(title: "Alert !!!",subTile: "Password must be 10 characters !",);
}
);
}else if(passController.text.length > 0 && passController.text.length < 10){
isConfirm = true;
showDialog<void>(
context: context,
builder: (BuildContext dialogContext) {
return Alert(title: "Alert !!!",subTile: "Password doesn't match !",);
}
);
}
}
checkChanged() {
if (secretVal != null) {
setState(() {
isSave = true;
});
} else {
isSave = false;
}
}
bool isSave = false;
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
/* double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;*/
Provider.of<ThemeProvider>(context).themeMode == ThemeMode.dark
? 'DarkTheme'
: 'LightTheme';
return Scaffold(
// resizeToAvoidBottomInset: false,
body: _signUp(),
bottomNavigationBar: BottomAppBar(
elevation: 4,
child: Container(
height: 70,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(
child: MaterialButton(
height: 44,
onPressed: () {
FocusScope.of(context).requestFocus(FocusNode());
//check();
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
color: Color(0xFF2A3476),
elevation: 0,
highlightElevation: 0,
child: Container(
child: Text(
"Save",
style: TextStyle(
color: Color(0xFF2A3476),
fontSize: 15,
fontFamily: 'medium'),
),
),
),
),
],
),
),
),
),
/* bottomNavigationBar: Container(
padding: EdgeInsets.all(25.0),
decoration: BoxDecoration(color: Colors.white,
),
child: Row(
children: [
Expanded(
child: MaterialButton(
height: 44,
onPressed: () {
FocusScope.of(context).requestFocus(FocusNode());
*/ /* Navigator.push(context, SlidePageRoute(page:PasswordScreen()));*/ /*
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
color: _isButtonEnabled ? Color(0xFF2A3476) : Color(0x201E1E99),
elevation: 0,
highlightElevation: 0,
child: Container(
child: Text(
"Next",
style: TextStyle(color: m_fillColor,fontSize: 18,fontWeight: FontWeight.w600 ,
fontFamily: "regular",),
),
),
),
),
],
),
)*/
);
}
Widget _signUp() {
return Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF2A3476),
Color(0xFF2A3476),
],
begin: Alignment.topLeft,
end: Alignment.centerRight,
),
),
child: SingleChildScrollView(
child: Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 36.0, horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Create Password",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
fontFamily: "medium",
fontWeight: FontWeight.w800,
),
),
],
),
),
Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Steps to set your",
style: TextStyle(
fontSize: 22,
fontFamily: "regular",
fontWeight: FontWeight.w300,
color: Colors.black,
),
),
Text(
"password",
style: TextStyle(
fontSize: 22,
fontFamily: "regular",
fontWeight: FontWeight.w300,
color: Colors.black,
),
),
SizedBox(
height: 20.0,
),
Text(
'Secret Question',
style: TextStyle(
fontSize: 15,
fontFamily: "regular",
),
),
SizedBox(
height: 8.0,
),
Row(
children: [
Expanded(
child: InkWell(
onTap: () {
FocusScope.of(context)
.requestFocus(FocusNode());
secretDialogue();
},
child: Stack(
children: <Widget>[
TextField(
/* textInputAction: TextInputAction.next,*/
controller: sQuastionController,
enabled: false,
onChanged: (val) {
check(context);
},
decoration: InputDecoration(
labelText: secretVal == null
? "Select One"
: secretVal,
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "",
/* prefixIcon: Icon(
Icons.people_outline_rounded,
color: Colors.grey[600],
)*/
),
),
Positioned.directional(
textDirection: Directionality.of(context),
end: 0,
top: 0,
bottom: 0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
"assets/icons/ic_drop_arrow.png",
scale: 9,
)),
)
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Text(
'Answer',
style: TextStyle(
fontSize: 15,
fontFamily: "regular",
),
),
SizedBox(
height: 8.0,
),
GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: TextField(
/* keyboardType: TextInputType.emailAddress,*/
/* textInputAction: TextInputAction.next,*/
controller: answerQController,
onChanged: (val) {
check(context);
},
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "",
/*prefixIcon: Icon(
Icons.people_outline_rounded,
color: Color(0xFFE1E8F7),
)*/
),
),
),
SizedBox(
height: 20.0,
),
Text(
'Password',
style: TextStyle(
fontSize: 15,
fontFamily: "regular",
),
),
SizedBox(
height: 8.0,
),
GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: TextFormField(
/* keyboardType: TextInputType.emailAddress,*/
/* textInputAction: TextInputAction.next,*/
controller: passController,
onChanged: (val) {
check(context);
},
//password validation
/* validator: (val){
if(val!.isEmpty)
return 'Empty';
return null;
},*/
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "************",
),
),
),
SizedBox(
height: 20.0,
),
Text(
'Confirm Password',
style: TextStyle(
fontSize: 15,
fontFamily: "regular",
),
),
SizedBox(
height: 8.0,
),
GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: TextFormField(
textInputAction: TextInputAction.done,
controller: conPassController,
onChanged: (val) {
check(context);
},
//password validation
/* validator: (val){
if(val!.isEmpty)
return 'Empty';
if(val != _pass.text)
return 'Not Match';
return null;
},*/
decoration: InputDecoration(
contentPadding: EdgeInsets.all(8),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Color(0xFFE1E8F7),
hintText: "************",
),
),
),
SizedBox(
height: 20.0,
),
SizedBox(
height: 8.0,
),
SizedBox(
height: 200.0,
),
],
),
),
),
],
),
),
),
);
}
//
//Secret Qu Alert
List secretList = [
"-What’s your favorite team?",
"-What’s your astrological sign?",
"-What’s your favorite movie?",
"-What city were you born in?",
"-What was your first car?",
];
var secretVal;
void secretDialogue() {
showDialog<void>(
context: context,
// false = user must tap button, true = tap outside dialog
builder: (BuildContext dialogContext) {
return StatefulBuilder(builder: (context, setState) {
return Dialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
insetPadding: EdgeInsets.all(20),
child: Container(
padding: EdgeInsets.symmetric(vertical: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(secretList.length, (index) {
return InkWell(
onTap: () {
setState(() {
secretVal = secretList[index];
Navigator.pop(context);
});
},
child: Container(
height: 50,
padding: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.centerLeft,
child: Text(
secretList[index],
style: TextStyle(
fontSize: 18,
fontFamily: "medium",
),
),
),
);
})),
),
);
});
},
);
}
}

How to have the text from a selected item inside a text field in flutter

I have an edit function which displays in a dialog in my to do list app on flutter. When an item is selected to be edited, a dialog containing a TextField(to enter the new value of the selected item) and a button(to save the changes) appears. The goal is to have the text of the selected item on the TextField of the dialog, currently my code has a hintText inside the TextField that does display the value of the selected item but what I want to achieve is to have that in the controller.
If you didnt understood what I want to achieve see this edit function like instagram's one, when editing a post on instagram you don't have to type everything again instead when editing you have the original text of the post there. Well that is not happening on my app, when editing an item the TextField doesnt show anything. How can I make this work?
code related to the edit function
List<ToDoElement> _toDoItems = [];
TextEditingController _editController = TextEditingController();
void _editToDoItem(String newText, int index) {
setState(() {
_toDoItems[index].task = newText;
});
}
_editDialog(BuildContext context, int index) {
return showDialog(context: context, builder: (context){
return Dialog(
backgroundColor: Colors.transparent,
insetAnimationDuration:
const Duration(milliseconds: 800),
child: Container(
padding: EdgeInsets.all(20),
height: 180,
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 60,
child: TextField( // this is the textfield that I should have the text of the selected item inside.
controller: _editController,
autofocus: true,
autocorrect: false,
onSubmitted: (val) {
FocusScope.of(context).requestFocus(FocusNode());
_editToDoItem(val, index);
Navigator.of(context).pop();
},
decoration: InputDecoration(
hintText: '${_toDoItems[index].task}', //this hint text shows the value of the selected item, yhis is what I want to have but in the controller.
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
)
),
Container(
height: 65,
width: double.infinity,
margin: EdgeInsets.only(top: 5,),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('EDIT', style: TextStyle(fontSize: 18)),
onPressed: () {
_editToDoItem(_editController.text, index);
FocusScope.of(context).requestFocus(FocusNode());
Navigator.of(context).pop();
},
),
),
],
),
),
);
});
}
full main.dart
import 'package:flutter/material.dart';
class ToDoElement {
String task;
final DateTime timeOfCreation;
ToDoElement(this.task, this.timeOfCreation);
}
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<ToDoElement> _toDoItems = [];
TextEditingController _controller = TextEditingController();
TextEditingController _editController = TextEditingController();
void _addToDoItem(String task) {
if(task.isNotEmpty) {
setState(() {
_toDoItems.add(ToDoElement(task, DateTime.now()));
});
}
}
void _editToDoItem(String newText, int index) {
setState(() {
_toDoItems[index].task = newText;
});
}
void _removeTodoItem(int index) {
setState(() => _toDoItems.removeAt(index));
}
_editDialog(BuildContext context, int index) {
return showDialog(context: context, builder: (context){
return Dialog(
backgroundColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)
),
insetAnimationDuration:
const Duration(milliseconds: 800),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
padding: EdgeInsets.all(20),
height: 180,
width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 60,
child: TextField(
controller: _editController,
autofocus: true,
autocorrect: false,
onSubmitted: (val) {
FocusScope.of(context).requestFocus(FocusNode());
_editToDoItem(val, index);
Navigator.of(context).pop();
},
style: TextStyle(fontSize: 17,),
decoration: InputDecoration(
hintText: '${_toDoItems[index].task}',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
)
),
Container(
height: 65,
width: double.infinity,
margin: EdgeInsets.only(top: 5,),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('EDIT', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_editToDoItem(_editController.text, index);
FocusScope.of(context).requestFocus(FocusNode());
Navigator.of(context).pop();
},
),
),
],
),
),
);
});
}
Widget _buildToDoItem(String toDoText, int index) {
return SizedBox(
child: Container(
height: 58,
margin: EdgeInsets.only(left: 22.0, right: 22.0, bottom: 12,),
decoration: BoxDecoration(
border: Border.all(width: 1.5, color: Colors.red),
borderRadius: BorderRadius.all(Radius.circular(18)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children:[
Expanded(
child: ListTile(
title: Text(
toDoText,
style: TextStyle(fontSize: 18),
),
onTap: () => null,
),
),
FlatButton(
child: Text('Edit', style: TextStyle(color: Colors.red, fontSize: 16.5),),
onPressed: () => _editDialog(context, index),
),
FlatButton(
child: Text('Delete', style: TextStyle(color: Colors.red, fontSize: 16.5),),
onPressed: () => _removeTodoItem(index),
),
],
),
),
);
}
int compareElement(ToDoElement a, ToDoElement b) =>
a.timeOfCreation.isAfter(b.timeOfCreation) ? -1 : 1;
Widget _buildToDoList() {
_toDoItems.sort(compareElement);
return Expanded(
child: ListView.builder(
itemCount: _toDoItems.length,
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index].task, index);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text('To Do List', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold,),),
)
),
backgroundColor: Colors.white,
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 60,
margin: EdgeInsets.all(22),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Container(
height: double.infinity,
child: TextField(
controller: _controller,
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
_controller.clear();
},
style: TextStyle(fontSize: 18,),
decoration: InputDecoration(
hintText: 'Add a task here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
),
),
),
Expanded(
flex: 4,
child: Container(
height: double.infinity,
margin: EdgeInsets.only(left: 12),
child: RaisedButton(
textColor: Colors.white,
color: Colors.red,
child: Text('ADD', style: TextStyle(fontSize: 18)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
onPressed: () {
_addToDoItem(_controller.text);
_controller.clear();
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
),
],
),
),
_buildToDoList()
]
),
),
);
}
}
If you have any questions please let me know in the comments;)
You already have the _editController variable. You can use it not only to get the typed text but also to set it:
You can do it before calling the edit function, for example:
[...]
onPressed: () {
_editController.text = toDoText;
_editDialog(context, index);
},
[...]
(Or maybe before creating the dialog, if you prefer.)
As you can see in the documentation:
A TextEditingController can also be used to provide an initial value for a text field. If you build a text field with a controller that already has text, the text field will use that text as its initial value.