Flutter: The method '/' was called on null. Receiver: null Tried calling: /(1080.0) - flutter

I'm getting this error since I've used Media Query for setting up Responsive UI. Below is the error that I'm getting in the terminal.
I don't know which method calling is returning null according to Dart. Because I'm navigating to new Screen via Raised Button and it is showing this error on Constructor of Widget/Class that I called on onPressed of the button
Here is the code of my class from where I'm navigating to new Screen of Doctor's Login:
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:medkit/animations/fadeAnimation.dart';
import 'package:medkit/animations/bottomAnimation.dart';
import 'package:medkit/doctor/doctorLogin.dart';
import 'package:medkit/doctor/doctorPanel.dart';
import 'aboutUs.dart';
class UserType extends StatelessWidget {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
Future<bool> _onWillPop() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)
),
title: new Text(
"Exit Application",
style: TextStyle(fontWeight: FontWeight.bold),
),
content: new Text("Are You Sure?"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
FlatButton(
shape: StadiumBorder(),
color: Colors.white,
child: new Text(
"Close",
style: TextStyle(color: Colors.blue),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
shape: StadiumBorder(),
color: Colors.white,
child: new Text(
"Yes",
style: TextStyle(color: Colors.red),
),
onPressed: () {
exit(0);
},
),
],
),
)) ??
false;
}
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: width * 0.04),
child: Column(
children: <Widget>[
SizedBox(
height: height * 0.08,
),
FadeAnimation(
0.3,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Category',
style: TextStyle(color: Colors.black, fontSize: 30),
),
GestureDetector(
onTap: () => _exitAlert(context),
child: Icon(
Icons.exit_to_app,
size: height * 0.04,
),
)
],
),
),
SizedBox(height: height * 0.09),
Column(
children: <Widget>[
FadeAnimation(
0.4,
CircleAvatar(
backgroundColor: Colors.black.withOpacity(0.2),
radius: height * 0.075,
child: Image(image: AssetImage("assets/doctor.png")),
),
),
WidgetAnimator(patDocBtn('Doctor', context)),
SizedBox(
height: height * 0.1,
),
FadeAnimation(
0.4,
CircleAvatar(
backgroundColor: Colors.black.withOpacity(0.2),
radius: height * 0.075,
child: Image(image: AssetImage("assets/patient.png")),
),
),
WidgetAnimator(patDocBtn('Patient', context)),
SizedBox(height: height * 0.13,),
GestureDetector(
onTap: () => Navigator.push(context, new MaterialPageRoute(builder: (context) => AboutUs())),
child: Column(
children: <Widget>[
Text('Version', style: TextStyle(fontWeight: FontWeight.bold),),
Text('V 0.1', style: TextStyle(fontSize: 12),)
],
),
),
SizedBox(height: 5,)
],
)
],
),
),
),
),
);
}
Widget patDocBtn(String categoryText, context) {
return Container(
width: MediaQuery.of(context).size.width * 0.5,
child: RaisedButton(
onPressed: () {
if (categoryText == 'Doctor') {
Navigator.pushNamed(context, 'DoctorLogin');
} else {
Navigator.pushNamed(context, 'PatientLogin');
}
},
color: Colors.white,
child: Text("I am " + categoryText),
shape: StadiumBorder(),
),
);
}
_exitAlert(context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)
),
title: new Text(
"Exit Application",
style: TextStyle(fontWeight: FontWeight.bold),
),
content: new Text("Are You Sure?"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
FlatButton(
color: Colors.white,
child: new Text(
"Close",
style: TextStyle(color: Colors.blue),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
color: Colors.white,
child: new Text(
"Yes",
style: TextStyle(color: Colors.red),
),
onPressed: () {
exit(0);
},
),
],
);
},
);
}
}
And here is Doctor's Login class code
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:medkit/animations/fadeAnimation.dart';
import 'package:medkit/animations/bottomAnimation.dart';
import 'package:medkit/doctor/doctorPanel.dart';
import 'package:medkit/otherWidgetsAndScreen/backBtn.dart';
import 'package:medkit/otherWidgetsAndScreen/imageAvatar.dart';
import 'package:toast/toast.dart';
class DoctorLogin extends StatefulWidget {
#override
_DoctorLoginState createState() => _DoctorLoginState();
}
class _DoctorLoginState extends State<DoctorLogin> {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
Future<FirebaseUser> _signIn(BuildContext context) async {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
FirebaseUser userDetails =
await _firebaseAuth.signInWithCredential(credential);
ProviderDoctorDetails providerInfo =
new ProviderDoctorDetails(userDetails.providerId);
List<ProviderDoctorDetails> providerData =
new List<ProviderDoctorDetails>();
providerData.add(providerInfo);
DoctorDetails details = new DoctorDetails(
userDetails.providerId,
userDetails.displayName,
userDetails.photoUrl,
userDetails.email,
providerData,
);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DoctorPanel(
detailsUser: details,
)));
return userDetails;
}
#override
Widget build(BuildContext context) {
final nameTextFieldController = TextEditingController();
final nameTextField = TextField(
keyboardType: TextInputType.text,
autofocus: false,
maxLength: 30,
textInputAction: TextInputAction.next,
onSubmitted: (_) => FocusScope.of(context).nextFocus(),
controller: nameTextFieldController,
decoration: InputDecoration(
fillColor: Colors.black.withOpacity(0.07),
filled: true,
labelText: 'Enter Name',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(const Radius.circular(20)))),
);
final phNumberTextController = TextEditingController();
final phoneTextField = TextField(
keyboardType: TextInputType.phone,
autofocus: false,
maxLength: 11,
controller: phNumberTextController,
textInputAction: TextInputAction.next,
onSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
filled: true,
fillColor: Colors.black.withOpacity(0.07),
labelText: 'Enter Number',
prefixIcon: Icon(Icons.phone),
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(const Radius.circular(20)),
),
),
);
final cnicTextController = TextEditingController();
final cnicTextField = TextFormField(
keyboardType: TextInputType.number,
autofocus: false,
maxLength: 13,
controller: cnicTextController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.black.withOpacity(0.07),
labelText: 'Enter CNIC',
prefixIcon: Icon(Icons.card_membership),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(20))),
);
final double width = MediaQuery.of(context).size.width;
final double height = MediaQuery.of(context).size.height;
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
resizeToAvoidBottomPadding: false,
body: SafeArea(
child: Container(
width: width,
height: height,
child: Stack(
children: <Widget>[
ImageAvatar(
assetImage: 'assets/bigDoc.png',
),
Container(
width: width,
height: height,
margin: EdgeInsets.fromLTRB(width * 0.03, 0, width * 0.03, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
BackBtn(),
SizedBox(height: height * 0.05,),
Text(
"\t\tLogin",
style: GoogleFonts.abel(
fontSize: ScreenUtil.instance.setSp(35),
fontWeight: FontWeight.bold),
),
SizedBox(
height: height * 0.05,
),
WidgetAnimator(nameTextField),
WidgetAnimator(phoneTextField),
WidgetAnimator(cnicTextField),
SizedBox(height: height * 0.01,),
FadeAnimation(
1.5,
SizedBox(
width: width,
height: height * 0.07,
child: RaisedButton(
color: Colors.white,
shape: StadiumBorder(),
onPressed: () {
if (nameTextFieldController.text != "" ||
phNumberTextController.text != "" ||
cnicTextController.text != "") {
Firestore.instance
.collection('doctorInfo')
.document(nameTextFieldController.text)
.setData({
'cnic': cnicTextController.text,
'phoneNumber': phNumberTextController.text,
});
_signIn(context)
.then((FirebaseUser user) =>
print('Gmail Logged In'))
.catchError((e) => print(e));
nameTextFieldController.clear();
cnicTextController.clear();
phNumberTextController.clear();
} else {
Toast.show('Fields Cannot be Empty!', context,
backgroundColor: Colors.red,
gravity: Toast.CENTER,
duration: Toast.LENGTH_SHORT);
}
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage('assets/google.png'),
height: ScreenUtil.instance.setHeight(35),
),
SizedBox(width: ScreenUtil.instance.setWidth(15)),
Text(
'Login',
style: TextStyle(
letterSpacing: 2,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.instance.setSp(18)),
)
],
),
),
),
),
SizedBox(height: height * 0.02,),
FadeAnimation(
2,
Text(
'You Will be asked Question regarding your Qualifications!', textAlign: TextAlign.center,
style: TextStyle(color: Colors.black.withOpacity(0.5),),
),
),
],
),
),
],
),
),
)),
);
}
}
class DoctorDetails {
final String providerDetails;
final String userName;
final String photoUrl;
final String userEmail;
final List<ProviderDoctorDetails> providerData;
DoctorDetails(this.providerDetails, this.userName, this.photoUrl,
this.userEmail, this.providerData);
}
class ProviderDoctorDetails {
ProviderDoctorDetails(this.providerDetails);
final String providerDetails;
}

Solution
I was using Media Query along with a 3rd party dependency at same time. I just removed that Dependency and its use in my code and it solved
Conclusion
Probably you can't use Media Query along with third party dependency at same time for making your app responsive

Your pushNamed route, the route name starts with '/'? Did you declare it as '/NAMEOFTHEROUTE'?
If yes please use your pushNamed as'/NAMEOFTHEROUTE'.

Related

Duplicate global key detected in widget tree

I am facing a problem duplicate global key detected in widget tree when I use static keyword with global key.
If I don't use this static keyword then keyboard hides automatically after few seconds. What should I do?
This is the code that I have tried
`import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:semesterproject/forgetpassword.dart';
import 'package:semesterproject/home.dart';
import 'package:semesterproject/signup.dart';
import 'package:semesterproject/textfielddec.dart';
class login extends StatelessWidget {
const login({super.key});
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.purpleAccent,
Colors.lightBlue,
Colors.indigoAccent
]),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width * 0.8,
child: CustomForm(),
))),
);
}
}
class CustomForm extends StatefulWidget {
const CustomForm({super.key});
#override
State<CustomForm> createState() => _CustomFormState();
}
class _CustomFormState extends State<CustomForm> {
static final _formkey = GlobalKey<FormState>();
final TextEditingController passcontroller = TextEditingController();
final TextEditingController emailcontroller = TextEditingController();
bool passvisibility = true;
FirebaseAuth _auth = FirebaseAuth.instance;
var errormessage1 = null, errormessage2 = null;
void setpassvisibility() {
setState(() {
passvisibility = !passvisibility;
});
}
Future<void> login() async {
if (_formkey.currentState!.validate()) {
_formkey.currentState!.save();
try {
await _auth
.signInWithEmailAndPassword(
email: emailcontroller.text, password: passcontroller.text)
.then((value) => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage(),
)));
} on FirebaseAuthException catch (error) {
if (error.code == 'wrong-password') {
setState(() {
errormessage1 = "Incorrect Password!";
});
} else {
setState(() {
errormessage1 = null;
});
}
if (error.code == 'user-not-found') {
setState(() {
errormessage2 = "User email not found";
});
} else {
setState(() {
errormessage2 = null;
});
}
}
}
}
#override
Widget build(BuildContext context) {
return Form(
key: _formkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Login to your Account",
style: TextStyle(
fontSize: 31,
fontWeight: FontWeight.bold,
color: Colors.cyanAccent),
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextFormField(
controller: emailcontroller,
style: TextStyle(fontSize: 22),
decoration: InputDecoration(
errorText: errormessage2,
focusedBorder: getfocusedborder(),
enabledBorder: getenabledborder(),
errorBorder: geterrorborder(),
focusedErrorBorder: geterrorfocusedborder(),
hintText: "Email",
hintStyle: TextStyle(fontSize: 22),
errorStyle: TextStyle(fontSize: 18),
),
validator: (value) {
if (value!.isEmpty) return "this field is required";
if (EmailValidator.validate(value) == false)
return "Please enter a valid email";
return null;
},
),
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextFormField(
style: TextStyle(fontSize: 22),
controller: passcontroller,
obscureText: passvisibility,
decoration: InputDecoration(
errorText: errormessage1,
focusedBorder: getfocusedborder(),
enabledBorder: getenabledborder(),
errorBorder: geterrorborder(),
focusedErrorBorder: geterrorfocusedborder(),
hintText: "Password",
hintStyle: TextStyle(fontSize: 22),
errorStyle: TextStyle(fontSize: 18),
suffixIcon: IconButton(
onPressed: setpassvisibility,
icon: passvisibility
? Icon(
Icons.visibility_off,
color: Colors.black,
)
: Icon(Icons.visibility),
color: Colors.black,
)),
validator: (value) {
if (value!.isEmpty) return "this field is required";
return null;
},
),
),
InkWell(
child: Text("Forgot password?",
style: TextStyle(color: Colors.amberAccent, fontSize: 22)),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => forgetpass(),
)),
),
SizedBox(
width: 280,
height: 50,
child: ElevatedButton(
onPressed: () => login(),
child: Text(
"Login",
style: TextStyle(fontSize: 22),
),
style: ElevatedButton.styleFrom(backgroundColor: Colors.indigo),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Don't have an account?",
style: TextStyle(fontSize: 22, color: Colors.amberAccent),
textAlign: TextAlign.center,
),
InkWell(
child: Text("Signup",
style: TextStyle(color: Colors.amber, fontSize: 20)),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Signup(),
)),
)
],
),
],
),
);
}
}`
I have go through with different posts of this error but I can't get the solution

Login is not working in flutter with REST API

Hi in the below code when I enter my mobile number, password and then click on the login button nothing is happening. My API working in Postman is not working here.
When I press the button it is not working, Entering a valid mobile number and password are not working.
Can anyone help me to find where I did any mistakes?
Login_screen.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sample_live/home_screen.dart';
import 'package:sample_live/model/login_model.dart';
import 'package:sample_live/splash_screen.dart';
import 'package:sample_live/login_otp.dart';
import 'ProgressHUD.dart';
import 'api/api_service.dart';
class LoginScreen extends StatefulWidget {
String name;
LoginScreen({this.name});
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final mobileController = TextEditingController();
final passwordController = TextEditingController();
LoginRequestModel requestModel;
bool isApiCallProcess = false;
GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
LoginRequestModel loginRequestModel;
final scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState(){
super.initState();
requestModel=new LoginRequestModel();
}
#override
Widget build(BuildContext context) {
return ProgressHUD(
child: _uiSetup(context),
inAsyncCall: isApiCallProcess,
opacity: 0.3,
);
}
Widget _uiSetup(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login", style: TextStyle(color: Colors.white)),
centerTitle: true,
),
body:
Stack(
children: [
Padding(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/hand.png',),
Padding(
padding: EdgeInsets.all(10),
child: Text("Welcome Doctor! ",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold
),),
),
Padding(
padding: EdgeInsets.all(10),
),
Text("Let's treat everyone great",
style: TextStyle(
color: Colors.black,
fontSize: 15,
),),
Padding(
padding: EdgeInsets.all(10),
),
TextFormField(
minLines: 1,
keyboardType: TextInputType.number,
onSaved: (input) => loginRequestModel.Mobile = input,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: "Enter Mobile No.",
hintText: "Enter Mobile No.",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0)))),
),
SizedBox(
height: 10,
),
TextFormField(
onSaved: (input) =>
loginRequestModel.Password = input,
validator: (input) =>
input.length < 3
? "Password should be more than 3 characters"
: null,
minLines: 1,
obscureText: true,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: "Password",
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0)))),
),
SizedBox(
height: 10,
),
Container(
width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
margin: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30)
),
child: RaisedButton(
color: Color(0xFF0769AA),
onPressed: () {
if (validateAndSave()) {
print(loginRequestModel.toJson());
setState(() {
isApiCallProcess = true;
});
APIService apiService = new APIService();
apiService.login(loginRequestModel).then((value) {
if (value != null) {
setState(() {
isApiCallProcess = false;
});
if (value.Status.isNotEmpty) {
final snackBar = SnackBar(
content: Text("Login Successful"));
scaffoldKey.currentState
.showSnackBar(snackBar);
} else {
final snackBar =
SnackBar(content: Text(value.Message));
scaffoldKey.currentState
// ignore: deprecated_member_use
.showSnackBar(snackBar);
}
}
});
}
},
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
height: 10,
),
Text("Or",
style: TextStyle(
color: Colors.black,
fontSize: 15,
),),
Container(
width: double.infinity,
child: FlatButton(
color: Color(0xFF0769AA),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => LoginOtp("Welcome")),
(route) => false);
},
child: Text(
"Login With OTP",
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: () {
// write your function
Navigator.push(
context,
MaterialPageRoute(
builder: (contex) => SplashScreen()));
},
child: Text(
"Forgot Password",
style: TextStyle(
color: Colors.blue,
fontSize: 16,
fontWeight: FontWeight.bold,
)
)),
],
),
],
),
),
Container(
alignment: Alignment.bottomCenter,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"By logging in or signing up, you agree to the",
textAlign: TextAlign.end,
style: TextStyle(
color: Colors.black,
fontSize: 12,
),
),
Text(
"Privacy Policy & Terms and Condition",
textAlign: TextAlign.end,
style: TextStyle(
color: Colors.blue,
fontSize: 12,
),
),
],
)
)
]),
);
}
bool validateAndSave() {
final form = globalFormKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
}

!_debugLocked is not true when making changes

I'm getting this error when i make any changes to my app, i need to re run my app to get rid of this error. I tried to make some changes to my navigation but nothing changes. I also i'm searching for hours on the google to find something useful but i can't find anything to make it work.
Note: I'm beginner on Flutter development
Main.dart:
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tasker/screens/HomeScreen.dart';
import 'package:progress_dialog/progress_dialog.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginDemo(),
);
}
}
class LoginDemo extends StatefulWidget {
#override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
late ProgressDialog progressDialog;
FirebaseAuth auth = FirebaseAuth.instance;
String email = "";
String password = "";
#override
Widget build(BuildContext context) {
progressDialog = ProgressDialog(context);
Future<String> getCurrentUserEmail() async {
FirebaseUser user = await auth.currentUser();
String userEmail = user.email.toString();
return userEmail;
}
// Navigate user to HomeScreen if already singed in
if (auth.currentUser() != null) {
Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => HomeScreen(userEmail: '',)));
}
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login"),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
/*
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(50.0)),*/
child: Image(
image: NetworkImage('https://cdn-icons-png.flaticon.com/512/1055/1055672.png'),
)),
),
),
Padding(
padding: const EdgeInsets.only(left:15.0, right: 15.0, top:30, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.email = value;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.password = value;
});
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter password'),
),
),
TextButton(
onPressed: (){
// open reset password screen
},
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(20)),
child: TextButton (
onPressed: () async {
progressDialog.show();
try {
AuthResult authResult = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email.toString(),
password: password.toString()
);
FirebaseUser user = authResult.user;
if (user == null) {
progressDialog.hide();
print("logged in");
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => HomeScreen(userEmail: '',)));
}
} catch (e) {
print(e.toString());
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
TextButton(
onPressed: (){
// open reset password screen
},
child: Text(
'New user? Sign up!',
style: TextStyle(color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold),
),
),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
},),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat
);
}
}
I found multiple issues with the code, but the one which caused the debugLocked error was using future directly inside the build method, you either put the future in a FutureBuilder or run outside the build method.
Here is the code fixed:
import 'dart:io';
import 'package:tasker/screens/HomeScreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_progress_dialog/flutter_progress_dialog.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginDemo(),
);
}
}
class LoginDemo extends StatefulWidget {
#override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
late ProgressDialog progressDialog;
FirebaseAuth auth = FirebaseAuth.instance;
String email = "";
String password = "";
Future<String>? getCurrentUserEmail() async {
User user = await auth.currentUser!;
String userEmail = user.email.toString();
return userEmail;
}
// Navigate user to HomeScreen if already singed in
#override
void initState() {
progressDialog = ProgressDialog(
child: Container(
child: Text('Loading'),
),
);
// TODO: implement initState
super.initState();
}
Future<void>? checkUserLoggedIn() async {
if (auth.currentUser != null) {
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (context) => HomeScreen(
userEmail: '',
)));
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login"),
),
body: ProgressDialog(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
child: Image(
image: NetworkImage(
'https://cdn-icons-png.flaticon.com/512/1055/1055672.png'),
)),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 30, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.email = value;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.password = value;
});
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter password'),
),
),
TextButton(
onPressed: () {
// open reset password screen
},
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () async {
showProgressDialog();
try {
UserCredential authResult = await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: email.toString(),
password: password.toString());
User user = authResult.user!;
if (user == null) {
dismissProgressDialog();
print("logged in");
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (context) => HomeScreen(
userEmail: '',
)));
}
} catch (e) {
print(e.toString());
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
TextButton(
onPressed: () {
// open reset password screen
},
child: Text(
'New user? Sign up!',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat);
}
}

How to navigate from login to home page with Firebase flutter

In the welcome screen, I have two button which is login and register. For the first time, when i try to login to the login screen, it did not navigate to the Home Page. For the second try, I want to login again, it can't back to the login page (stuck at Welcome Screen). Can anyone help me? Thank you
Welcome Screen Code:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
navigateToLogin() async {
Navigator.pushReplacementNamed(context, "Login");
}
navigateToRegister() async {
Navigator.pushReplacementNamed(context, "SignUp");
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: <Widget>[
SizedBox(height: 35.0),
Container(
height: 400,
child: Image(
image: AssetImage("assets/girlsave.png"),
fit: BoxFit.contain,
),
),
SizedBox(height: 20),
RichText(
text: TextSpan(
text: 'Welcome to ',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Colors.orange),
children: <TextSpan>[
TextSpan(
text: 'MONGER!',
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
color: Colors.orange))
])),
SizedBox(height: 10.0),
Text(
'Your Personal Money Tracker',
style: TextStyle(color: Colors.black),
),
SizedBox(height: 30.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
padding: EdgeInsets.only(left: 30, right: 30),
onPressed: navigateToLogin,
child: Text(
'LOGIN',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.orange),
SizedBox(width: 20.0),
RaisedButton(
padding: EdgeInsets.only(left: 30, right: 30),
onPressed: navigateToRegister,
child: Text(
'REGISTER',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.orange),
],
),
SizedBox(height: 20.0),
],
),
),
);
}
}
Login Page Code:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _email, _password;
checkAuthentification() async {
_auth.authStateChanges().listen((user) {
if (user != null) {
print(user);
Navigator.pushReplacementNamed(context, "/");
}
});
}
#override
void initState() {
super.initState();
this.checkAuthentification();
}
login() async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
try {
await _auth.signInWithEmailAndPassword(
email: _email, password: _password);
} catch (e) {
showError(e.message);
print(e);
}
}
}
showError(String errormessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('ERROR'),
content: Text(errormessage),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'))
],
);
});
}
navigateToSignUp() async {
Navigator.push(context, MaterialPageRoute(builder: (context) => SignUpPage()));
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
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 'Enter Email';
},
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email)),
onSaved: (input) => _email = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.length < 6)
return 'Provide Minimum 6 Character';
},
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
onSaved: (input) => _password = input),
),
SizedBox(height: 20),
RaisedButton(
padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
onPressed: login,
child: Text('LOGIN',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
color: Colors.orange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
)
],
),
),
),
GestureDetector(
child: Text('Create an Account?'),
onTap: navigateToSignUp,
)
],
),
),
));
}
}
Sign Up code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignUpPage extends StatefulWidget {
#override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
FirebaseAuth _auth = FirebaseAuth.instance;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _username, _email, _password;
checkAuthentication() async {
_auth.authStateChanges().listen((user) async {
if (user != null) {
Navigator.pushReplacementNamed(context, "/");
}
});
}
#override
void initState() {
super.initState();
this.checkAuthentication();
}
signUp() async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
try {
UserCredential user = await _auth.createUserWithEmailAndPassword(
email: _email, password: _password);
if (user != null) {
// UserUpdateInfo updateuser = UserUpdateInfo();
// updateuser.displayName = _name;
// user.updateProfile(updateuser);
await _auth.currentUser.updateProfile(displayName: _username);
// await Navigator.pushReplacementNamed(context,"/") ;
}
} catch (e) {
showError(e.message);
print(e);
}
}
}
showError(String errormessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('ERROR'),
content: Text(errormessage),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'))
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
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 'Enter Username';
},
decoration: InputDecoration(
labelText: 'Username',
prefixIcon: Icon(Icons.person),
),
onSaved: (input) => _username = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Enter Email';
},
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email)),
onSaved: (input) => _email = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.length < 6)
return 'Provide Minimum 6 Character';
},
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
onSaved: (input) => _password = input),
),
SizedBox(height: 20),
RaisedButton(
padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
onPressed: signUp,
child: Text('SignUp',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
color: Colors.orange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
)
],
),
),
),
],
),
),
));
}
}
Main Code:
import 'package:flutter/material.dart';
import 'package:monger_app/WelcomeScreen/login.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
import 'package:monger_app/WelcomeScreen/welcome_screen.dart';
import 'package:monger_app/page/root.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: primary
),
debugShowCheckedModeBanner: false,
home:
WelcomeScreen(),
routes: <String,WidgetBuilder>{
"Login" : (BuildContext context)=>LoginPage(),
"SignUp":(BuildContext context)=>SignUpPage(),
"start":(BuildContext context)=>Root(),
},
);
}
}
HomePage Code
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:monger_app/page/setting.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:animated_bottom_navigation_bar/animated_bottom_navigation_bar.dart';
import 'package:monger_app/page/transaction.dart';
import 'package:monger_app/page/statistics.dart';
import 'package:monger_app/page/account.dart';
import 'package:monger_app/page/record.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Root extends StatefulWidget {
#override
_RootState createState() => _RootState();
}
class _RootState extends State<Root> {
final FirebaseAuth _auth = FirebaseAuth.instance;
User user;
bool isloggedin = false;
checkAuthentification() async {
_auth.authStateChanges().listen((user) {
if (user == null) {
Navigator.of(context).pushReplacementNamed("start");
}
});
}
int pageIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: getBody(),
bottomNavigationBar: getFooter(),
floatingActionButton: FloatingActionButton(
onPressed: (){
setTabs(4);
},
child: Icon(Icons.add, size: 25),
backgroundColor: primary,
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
Widget getBody(){
return IndexedStack(
index: pageIndex,
children: [
Transaction(),
Statistics(),
Account(),
Settings(),
Record()
],
);
}
Widget getFooter(){
List<IconData> iconItems = [
Ionicons.md_bookmarks,
Ionicons.md_stats,
Ionicons.md_wallet,
Ionicons.ios_settings,
];
return AnimatedBottomNavigationBar(
activeColor: primary,
splashColor: secondary,
inactiveColor: Colors.black.withOpacity(0.5),
icons: iconItems,
activeIndex: pageIndex,
gapLocation: GapLocation.center,
notchSmoothness: NotchSmoothness.softEdge,
leftCornerRadius: 10,
iconSize: 25,
rightCornerRadius: 10,
onTap: (index) {
setTabs(index);
});
}
setTabs(index) {
setState(() {
pageIndex = index;
});
}
}
You have this code:
Navigator.pushReplacementNamed(context, "/");
but you do not have the named route "/" registered.
From your code, your Home Page is registered as "start".
So you should update the name of the route to "start" and that should work.
Your updated code should be as below:
Navigator.pushReplacementNamed(context, "start");

Flutter General dialog box - set state not working

I have an issue with my General Dialog Box. I would like to display a star. Then I would like to change it state when the star is taped and replace the icon by a yellow Star.
But is does not work. The Dialog Box is not refreshed so the icon is not changing. Please, can you look at the source code below and point me into the right direction please?
Many thanks.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:date_time_picker/date_time_picker.dart';
import 'package:gtd_official_sharped_focused/snackbar.dart';
String _isImportantInboxTask ;
String _isUrgentInboxTask ;
String inboxTaskDisplayed;
String isImportant = "false" ;
String isUrgent = "false" ;
String myProjectName ;
var taskSelectedID;
//---------------
//String _initialValue;
//_-----------------
var documentID;
var textController = TextEditingController();
var popUpTextController = TextEditingController();
class Inbox extends StatefulWidget {
Inbox({Key key}) : super(key: key);
#override
_InboxState createState() => _InboxState();
}
class _InboxState extends State<Inbox> {
GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();
bool isOn = true;
#override
Widget build(BuildContext context) {
void showAddNote() {
TextEditingController _noteField = new TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 4,
child: Column(
children: [
TextField(
controller: _noteField,
maxLines: 4,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.black, width: 1.0),
),
),
),
SizedBox(height: 10),
Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
child: MaterialButton(
minWidth: MediaQuery.of(context).size.width / 1.5,
onPressed: () {
Navigator.of(context).pop();
CollectionReference users = FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.add({'task_Name': _noteField.text,'task_Status': 'Inbox' })
.then((value) => print("User Document Added"))
.catchError((error) =>
print("Failed to add user: $error"));
},
padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
child: Text(
'Add Note',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
);
});
}
return Scaffold(
appBar: new AppBar(
title: new Text('Inbox Page'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add_circle_outline,
color: Colors.white,
),
onPressed: () {
showAddNote();
// do something
},
),
],
),
drawer: MyMenu(),
backgroundColor: Colors.white,
body: Column(
//mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: MediaQuery.of(context).size.height / 1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.where('task_Status', isEqualTo: 'Inbox')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
return Wrap(
children: [Card(
child: SwipeActionCell(
key: ObjectKey(document.data()['task_Name']),
actions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.doc(document.id)
.delete()
.then((value) => print("Note Deleted"))
.catchError((error) => print(
"Failed to delete Task: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Image.asset('assets/icons/inbox.png'),
),
title: GestureDetector(
child: Text(
//'task_Name' correspond au nom du champ dans la table
document.data()['task_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
// Pour editer task
onDoubleTap: (){
taskSelectedID = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.doc(document.id);
//Dialog
return showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: Colors.black45,
transitionDuration: const Duration(milliseconds: 20),
pageBuilder: (BuildContext buildContext,
Animation animation,
Animation secondaryAnimation) {
return Scaffold(
appBar: AppBar(
title: Text ('Edit Task'),
leading: InkWell(
child: Icon(Icons.close),
onTap:(){Navigator.of(context).pop();}
),
actions: [Padding(
padding: const EdgeInsets.fromLTRB(0, 0,16.0,0),
child: InkWell(
child: Icon(Icons.save),
onTap: () {
final loFormInbox = _captureFormKey
.currentState;
if (loFormInbox.validate()) {
loFormInbox.save();
CollectionReference users = FirebaseFirestore
.instance
.collection(
'Users')
.doc(FirebaseAuth
.instance
.currentUser.uid)
.collection(
'allTasks');
users
.add({
'task_Name': _valueTaskNameSaved,
})
.then((value) =>
print(
"Task Created"))
.catchError((
error) =>
print(
"Failed to add task: $error"));
showSimpleFlushbar(
context,
'Task Saved',
_valueTaskNameSaved,
Icons
.mode_comment);
loFormInbox.reset();
isImportant = 'false';
isUrgent = 'false';
}
}
),
)],
),
body: Center(
child: Container(
width: MediaQuery.of(context).size.width - 10,
height: MediaQuery.of(context).size.height - 80,
padding: EdgeInsets.all(20),
color: Colors.white,
child: Column(
children: [
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
//Test Energy et Time / Important /urgent
Material(
child:
Container(
// color: Colors.red,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:[
//Important
FlatButton(
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
isImportant =="true" ? Icon(Icons.star,color: Colors.orange,) :
Icon(Icons.star_border, color: Colors.grey,),
// Icon(Icons.battery_charging_full),
Text('Important'),
],
)
),
onTap: () {
setState(() {
if (isImportant=='true'){
isImportant = 'false';}
else
{isImportant= 'true';
}
});
},
),
),
RaisedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Close",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
)
//++++++++++++++++
],
),
),
),
);
});
},
),
),
),
),
),
),
]
);
}).toList(),
);
}),
),
],
),
bottomNavigationBar: MyBottomAppBar(), //PersistentBottomNavBar(),
);
}
}
#override
Widget build(BuildContext context){
return _widget();
}
}
Thanks to your solution, I am able to do what I was willing to do. But now, I have an other issue. In the version 1 of my code, I am using this code
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
This part was working well. But after the modifications, I am getting an error. The error is about document.
Undefined name 'document'. Try correcting the name to one that is defined, or defining the name.
Please, can you help me with this so I can finalize this page. Thank you
So you want to change the color of icon on clicking it inside dialogBox,
but unfortunately you are using stateless widget Scaffold in return of showGeneralDialog builder so one thing that can possibly help is to make a separate StateFull Widget RatingDialogBox and use that in the builder.
Also instead of InkWell you can use IconButton
I will suggest you to use this package it is great
flutter_rating_bar
also feel free to comment is this doesn't satisfy your need