Navigator operation requested with a context that does not include a Navigator.(Flutter) - flutter

Hi I have a scenario where in I enter the username password based on the credentials it will redirect the user to second screen . I am not sure where did I got wrong? but I am getting this error below:
Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
Here is the code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'Animation/FadeAnimation.dart';
import 'AuthenticationService.dart';
import 'PatientList.dart';
class HomePage extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
gotoPatientList(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>PatientList()),
);
}
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationService>().authStateChanges,
),
],
child:MaterialApp(
home: SingleChildScrollView(
child:RaisedButton(
onPressed: () {
gotoPatientList(context);
context.read<AuthenticationService>().signIn(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill)),
child: Stack(
children: <Widget>[],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(
1.8,
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color:
Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10))
]),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[100]))),
child: TextField(
controller: emailController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])),
),
)
],
),
)),
SizedBox(
height: 30,
),
FadeAnimation(
2,
Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(colors: [
Color.fromRGBO(214, 0, 27, 1),
Color.fromRGBO(214, 0, 27, 1),
])),
child: Center(
child: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
)),
SizedBox(
height: 70,
),
FadeAnimation(
1.5,
Text(
"Forgot Password?",
style: TextStyle(
color: Color.fromRGBO(214, 0, 27, 1)),
)),
],
),
)
],
),
),
),
),
),
);
}
}
class AuthenticationWrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User>();
if (firebaseUser != null) {
return HomePage();
}
return PatientList();
}
}

You can wrap the button in builder to get the context of the app:
Builder(
builder: (context) => RaisedButton(
onPressed: () {
gotoPatientList(context);
context.read<AuthenticationService>().signIn(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
},
...
),
);

Related

Creating an flutter app in vs code with firebase its showing the specific errors .Errors that showing is mentioned below and the signup widget code

'The name UserRecord isn't a type so it can't be used as a type argument Try correcting the name to an existing type or defining a type named UserRecord
The method 'queryUserRecordOnce' isn't defined for the type '_SignupWidgetState'.
Try correcting the name to the name of an existing method, or defining a method named 'queryUserRecordOnce'
The method 'createUserRecordData' isn't defined for the type '_SignupWidgetState'.
Try correcting the name to the name of an existing method, or defining a method named 'createUserRecordData''
*import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'login.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
class SignupWidget extends StatefulWidget {
const SignupWidget({Key key}) : super(key: key);
#override
_SignupWidgetState createState() => _SignupWidgetState();
}
class _SignupWidgetState extends State<SignupWidget> {
TextEditingController emailTextController;
TextEditingController textController1;
TextEditingController textController2;
TextEditingController passwordTextController;
bool passwordVisibility;
var collection = FirebaseFirestore.instance.collection('UserRecord');
final auth = FirebaseAuth.instance;
final scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
emailTextController = TextEditingController();
textController1 = TextEditingController();
textController2 = TextEditingController();
passwordTextController = TextEditingController();
passwordVisibility = false;
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Align(
alignment: AlignmentDirectional(0.3, -0.8),
child: Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
color: Color(0xFFEEEEEE),
),
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(0, 100, 0, 0),
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: [
Align(
alignment: AlignmentDirectional(0.2, -0.35),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional(-0.55, -0.35),
child: InkWell(
onTap: () async {
Navigator.pop(context);
},
child: const FaIcon(
FontAwesomeIcons.arrowLeft,
color: Color.fromRGBO(5, 4, 0, 5),
size: 24,
),
),
),
),
const Expanded(
child: Align(
alignment: AlignmentDirectional(-2.5, -0.1),
child: Text(
'Signup',
style: TextStyle(
fontFamily: 'Oswald',
color: Color(0xFF0F5AA5),
fontSize: 40,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
Align(
alignment: AlignmentDirectional(0, 0),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Align(
alignment: AlignmentDirectional(0, 0.05),
child: Container(
width: 250,
height: 400,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF0F5AA5),
Color(0xFF0F5AA5),
],
stops: [0, 0, 1],
begin: AlignmentDirectional(0, -1),
end: AlignmentDirectional(0, 1),
),
),
alignment: AlignmentDirectional(
-0.09999999999999998, 0.5),
child: Align(
alignment: AlignmentDirectional(-0.1, 1),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
10, 15, 10, 0),
child: TextFormField(
controller: emailTextController,
onChanged: (_) => EasyDebounce.debounce(
'emailTextController',
Duration(milliseconds: 2000),
() => setState(() {}),
),
autofocus: true,
obscureText: false,
decoration: InputDecoration(
hintText: 'Mobile or Email',
hintStyle: const TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF000509),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
suffixIcon: emailTextController
.text.isNotEmpty
? InkWell(
onTap: () => setState(
() => emailTextController
?.clear(),
),
child: Icon(
Icons.clear,
color: Color(0xFF757575),
size: 22,
),
)
: null,
),
style: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF1A1F24),
),
),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
10, 10, 10, 0),
child: TextFormField(
controller: textController1,
onChanged: (_) => EasyDebounce.debounce(
'textController1',
Duration(milliseconds: 1000),
() => setState(() {}),
),
autofocus: true,
obscureText: false,
decoration: InputDecoration(
hintText: 'Full name',
hintStyle: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF000509),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
suffixIcon: textController1
.text.isNotEmpty
? InkWell(
onTap: () => setState(
() => textController1
?.clear(),
),
child: Icon(
Icons.clear,
color: Color(0xFF757575),
size: 22,
),
)
: null,
),
style: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF1A1F24),
),
textAlign: TextAlign.start,
),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
10, 10, 10, 0),
child: TextFormField(
controller: textController2,
onChanged: (_) => EasyDebounce.debounce(
'textController2',
Duration(milliseconds: 1000),
() => setState(() {}),
),
autofocus: true,
obscureText: false,
decoration: InputDecoration(
hintText: 'User name',
hintStyle: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF000509),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
suffixIcon: textController2
.text.isNotEmpty
? InkWell(
onTap: () => setState(
() => textController2
?.clear(),
),
child: Icon(
Icons.clear,
color: Color(0xFF757575),
size: 22,
),
)
: null,
),
style: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF1A1F24),
),
textAlign: TextAlign.start,
),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
10, 10, 10, 25),
child: FutureBuilder<List<UserRecord>>(
future: queryUserRecordOnce(
singleRecord: true,
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return const Center(
child: SizedBox(
width: 50,
height: 50,
child:
CircularProgressIndicator(
color: Colors.black,
),
),
);
}
List<UserRecord>
textFieldUserRecordList =
snapshot.data;
final textFieldUserRecord =
textFieldUserRecordList.isNotEmpty
? textFieldUserRecordList
.first
: null;
return TextFormField(
controller: passwordTextController,
onChanged: (_) =>
EasyDebounce.debounce(
'passwordTextController',
Duration(milliseconds: 1000),
() => setState(() {}),
),
autofocus: true,
obscureText: !passwordVisibility,
decoration: InputDecoration(
hintText: 'Password',
hintStyle: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF000509),
),
enabledBorder:
UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
focusedBorder:
UnderlineInputBorder(
borderSide: BorderSide(
color: Color(0xFF080F18),
width: 1,
),
borderRadius:
BorderRadius.circular(5),
),
suffixIcon: InkWell(
onTap: () => setState(
() => passwordVisibility =
!passwordVisibility,
),
focusNode: FocusNode(
skipTraversal: true),
child: Icon(
passwordVisibility
? Icons
.visibility_outlined
: Icons
.visibility_off_outlined,
color: Color(0xFF757575),
size: 22,
),
),
),
style: TextStyle(
fontFamily: 'Poppins',
color: Color(0xFF1A1F24),
),
textAlign: TextAlign.start,
);
},
),
),
Padding(
padding: EdgeInsetsDirectional.fromSTEB(
0, 0, 0, 30),
child: ElevatedButton(
onPressed: () async {
final user = await FirebaseAuth
.instance
.createUserWithEmailAndPassword(
email:
emailTextController.text,
password:
passwordTextController
.text);
if (user == null) {
return;
}
final userCreateData =
createUserRecordData(
username: textController2.text,
pass: passwordTextController.text,
email: emailTextController.text,
uid: textController1.text,
);
await UserRecord.collection
.doc(user.uid)
.update(userCreateData);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
LoginWidget(),
),
);
},
child: Text("signup"),
),
),
],
),
),
),
),
],
),
),
],
),
),
),
),
),
),
);
}
}*

No Material Widget found textfield widgets require a material widget ancestor(Flutter)

Hi I am trying to build a login screen in flutter but I am getting below error when opening it.
No material widget found textfield widgets require a material widget ancestor
class HomePage extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationService>().authStateChanges,
),
],
child:MaterialApp(
home: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill)),
child: Stack(
children: <Widget>[],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(
1.8,
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color:
Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10))
]),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[100]))),
child: TextField(
controller: emailController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])),
),
)
],
),
)),
SizedBox(
height: 30,
),
RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
side: BorderSide(color: Colors.red)),
onPressed: () {
gotoPatientList(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>PatientList()),
);
}
context.read<AuthenticationService>().signIn(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
gotoPatientList(context);
},
color: Color.fromRGBO(214, 0, 27,1),
textColor: Colors.white,
child: Text("Login".toUpperCase(),
style: TextStyle(fontSize: 14)),
),
Padding(padding:EdgeInsets.only(top: 15),
),
ClipOval(
child: RaisedButton(
onPressed: () {
gotoForgotPassword(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>ForgotPassword()),
);
}
gotoForgotPassword(context);
},
child: Text("Forgot Password"),
textColor: Colors.white,
color:Color.fromRGBO(214, 0, 27, 1),
),
),
],
),
)
],
),
),
),
),
);
}
}
In material design most widgets are conceptually printed on a sheet of material In flutter material library that material is represented by the Material widget that renders ink splashes
Wrap the SingleChildScrollView in a Builder:
Builder(
builder: (context) => SingleChildScrollView......
This is because the context you are using is not a child of MaterialApp.
A better solution will be to put MaterialApp in a widget MyApp for example, and use HomePage widget as home for the MaterialApp.
Also wrap the SingleChildScrollView inside Scaffold(body: SingleChild....

How do i center a text field horizontaly and vertically in flutter

Hi i am new to flutter i need to align the text field horizontally and vertically for more elaboration see this
What i am getting:
Text aligned at the very top it needs to be in the center
What i really want:
the text field is aligned both horizontaly and vertically that is exactly what i am looing for
Here is the code:
import 'package:multi_purpose_scope/Animation/FadeAnimation.dart';
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
)
);
class HomePage extends StatelessWidget {
gotoSecondActivity(BuildContext context){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondActivity()),
);
}
#override
Widget build(BuildContext context){
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: RaisedButton(
onPressed: () {
gotoSecondActivity(context);
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill
)
),
child: Stack(
children: <Widget>[
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(1.8, Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10)
)
]
),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(
color: Colors.grey[100]))
),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
obscureText: true,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
)
],
),
)),
SizedBox(height: 30,),
FadeAnimation(2, Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(
colors: [
Color.fromRGBO(214, 0, 27, 1),
Color.fromRGBO(214, 0, 27, 1),
]
)
),
child: Center(
child: Text("Login", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),),
),
)),
SizedBox(height: 70,),
FadeAnimation(1.5, Text("Forgot Password?",
style: TextStyle(
color: Color.fromRGBO(214, 0, 27, 1)),)),
],
),
)
],
),
),
)
),
);
}
}
class SecondActivity extends StatelessWidget {
gotoRegister(BuildContext context){
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>Register()),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Container(
height: 174,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/patient_list.png'),
)
),
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
height: 128,
child: Text(
'Patient List',
style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 30,
color: Colors.white
),
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
gotoRegister(context);
},
tooltip: 'Increment',
child: Icon(Icons.add),
backgroundColor: Color.fromRGBO(214, 0, 27,1),
),
),
);
}
}
class Register extends StatelessWidget {
goBack(BuildContext context) {
Navigator.pop(context);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child:Container(
height: 174,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/patient_list.png'),
)
),
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
height: 128,
child: Text(
'Registration
style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 30,
color: Colors.white
),
)
),
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(
color: Colors.grey[100]))
),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
),
],
),
),
)
),
);
}
}
I searched for this but cant seem to find the solution to my problem.
I have almost tried all the solutions that i can think of but those don't work
Just set the textAlign property to your TextField and also add a border in your decoration.
Sample:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: <Widget>[
const SampleTextField(hintText: 'Enter Name'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter MR-Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Phone Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Hospital Name'),
const SizedBox(height: 10),
FlatButton(
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
// materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
// visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(vertical: 20),
color: Colors.red,
child: const Center(
child: Text('Registration'),
),
),
],
),
),
),
),
);
}
}
class SampleTextField extends StatelessWidget {
const SampleTextField({
this.controller,
this.hintText = '',
});
final TextEditingController controller;
final String hintText;
#override
Widget build(BuildContext context) {
return TextField(
controller: controller,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(
width: 1,
color: Colors.black54,
),
),
hintText: hintText,
hintStyle: const TextStyle(
color: Colors.black54,
),
contentPadding: const EdgeInsets.only(left: 20),
),
// textAlign: TextAlign.center, // Align vertically and horizontally
);
}
}
You are using a stack widget so if you want to align and positioned your widget inside the stack see the below options
Wrap widget with Positioned widget if you want to change position
Wrap widget with Align widget for alignment
Check out this Video for how to use Positioned widget
Check out this Video for how to use Align widget

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.

How to edit a selected item from a list in 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()
]),
),
);
}
}