when dialog open and after close dialog when focus on textFormField widget rebuild unnecessarily and user doesn't able to put text in this - flutter

When I click on the update profile button I want to show a dialog if no changes are found, but when I close this and try to change the username or email again the entire widget rebuilds twice as soon as I focus on the TextFormField.
import 'dart:developer';
import 'package:chatappwithfirebase/Screens/profilescreen.dart';
import 'package:chatappwithfirebase/api/customtranscation.dart';
import 'package:chatappwithfirebase/widgets/imagepick.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../Screens/mainscreen.dart';
import '../utils/utils.dart';
class EditProfile extends StatefulWidget {
EditProfile({Key? key,required this.initialValues}) : super(key: key);
final Map<String,String> initialValues;
#override
State<EditProfile> createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
final _fromKey = GlobalKey<FormState>();
final firebase =FirebaseFirestore.instance.collection('users');
final firebaseAuth =FirebaseAuth.instance;
TextEditingController? txtEmail;
TextEditingController? txtUsername;
var updatedProfileImageLink;
File? selectedImage;
#override
void initState() {
txtEmail =TextEditingController(text: widget.initialValues['emailAddress']);
txtUsername =TextEditingController(text: widget.initialValues['username']);
super.initState();
}
void getImage(ImageSource imageSource)async{
ImagePicker picker =ImagePicker();
Navigator.of(context).pop();
var getImage= await picker.pickImage(source: imageSource);
selectedImage = await File(getImage!.path);
print(selectedImage!.path);
}
void updateProfile()async{
FocusScope.of(context).unfocus();
if(
widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null ||
widget.initialValues['emailAddress'] != txtEmail!.text ||
widget.initialValues['username'] != txtUsername!.text)
{
if (widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null) {
showDialog(
barrierDismissible: false,
context: context, builder: (context){
return AlertDialog(
content: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(width: 5,),
Text('Uploading...')
],
),
);
}).then((value) => setState((){}));
final storage =FirebaseStorage.instance.ref().child('User_image').child(firebaseAuth.currentUser!.uid +'.jpg');
await storage.putFile(selectedImage!);
updatedProfileImageLink = await storage.getDownloadURL();
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'imageUrl': updatedProfileImageLink}).then((value) => Navigator.of(context).pop());
}
if (widget.initialValues['emailAddress'] != txtEmail!.text) {
final userdata = await firebase.doc(firebaseAuth.currentUser!.uid).get();
await firebaseAuth.signInWithEmailAndPassword(
email: userdata['email'], password: userdata['password']);
await FirebaseAuth.instance.currentUser!.updateEmail(txtEmail!.text);
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'email': txtEmail!.text}).then((value) => showDialog(
context: context,
builder: (context){
return CupertinoAlertDialog(
title: CircleAvatar(
backgroundColor: Colors.green,
child: Icon(Icons.done,color: Colors.white,size: 30,)),
content: Text('Email Address Updated'),
actions: [
CupertinoDialogAction(
onPressed: (){
widget.initialValues['emailAddress'] =txtUsername!.text;
Navigator.of(context).pop();
},
child: Text('Ok')
)
],
);
}));
}
if (widget.initialValues['username'] != txtUsername!.text) {
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'username': txtUsername!.text}).then((value) => showDialog(
context: context,
builder: (context){
return CupertinoAlertDialog(
title: CircleAvatar(
backgroundColor: Colors.green,
child: Icon(Icons.done,color: Colors.white,size: 30,)),
content: Text('Username Updated'),
actions: [
CupertinoDialogAction(
onPressed: (){
widget.initialValues['username'] =txtUsername!.text;
Navigator.of(context).pop();
},
child: Text('ok')
),
],
);
})
);
}
}
else{
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Alert'),
content: const Text('Changes Not Found'),
// actions: <CupertinoDialogAction>[
// CupertinoDialogAction(
// //isDefaultAction: true,
// onPressed: () {
// Navigator.pop(context);
// },
// child: const Text('ok'),
// ),
// ],
),
);
}
}
void _showImagePickOptions(context){
showModalBottomSheet(
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft :Radius.circular(20),topRight:Radius.circular(20) )),
context: context,
builder: (context){
return Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
onTap:() => getImage(ImageSource.camera),
leading: const Icon(Icons.camera_enhance,color: Colors.pink,),
title: const Text('Capture Image',style: TextStyle(color: Colors.grey),),
),
ListTile(
onTap:() => getImage(ImageSource.gallery),
leading: const Icon(Icons.image_sharp,color: Colors.purple,),
title: const Text('Select Image',style: TextStyle(color: Colors.grey),)
)
],
),
);
});
}
#override
Widget build(BuildContext context) {
log('loaded');
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0,
title: Text('Edit Profile',style: TextStyle(color: Colors.black),),
leading: IconButton(onPressed: (){
Navigator.of(context).pop();
},icon: Icon(CupertinoIcons.back,color: iconColor,),),
actions: [
const Icon(Icons.more_vert,color: Colors.black,)
],
),
body: FutureBuilder(
future: firebase.doc(FirebaseAuth.instance.currentUser!.uid).get(),
builder: (context,userdata){
if(userdata.connectionState ==ConnectionState.waiting){
return Center(child: CircularProgressIndicator(color: accentColor,));
}
return Padding(
padding: EdgeInsets.all(20),
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: EdgeInsets.all(20),
child: Stack(
alignment: Alignment.bottomRight,
children: [
CircleAvatar(
radius: 60,
backgroundImage:updatedProfileImageLink == null ? NetworkImage(widget.initialValues['imageUrl']!) :
NetworkImage(updatedProfileImageLink)
),
CircleAvatar(
backgroundColor: accentColor,
child: IconButton(onPressed:()=> _showImagePickOptions(context),icon: Icon(Icons.camera_enhance,color: Colors.white,
),
),
)
]
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.04 ,),
Form(
key: _fromKey,
child: Column(
children: [
TextFormField(
controller: txtEmail,
decoration: InputDecoration(
prefixIcon: Icon(Icons.email),
label: Text('Email Address'),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.02,),
TextFormField(
controller: txtUsername,
decoration: InputDecoration(
labelStyle: TextStyle(fontFamily: 'Roboto'),
prefixIcon: Icon(Icons.supervised_user_circle_rounded),
label: Text('Username'),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
),
),
],
)),
SizedBox(height: MediaQuery.of(context).size.height * 0.03,),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: accentColor,
fixedSize: Size(200, 50)
),
onPressed: updateProfile,
child: Text('Update Profile'),),
],
),
),
);
}),
);
}
}
It works fine if I don't open a dialog, but when I do this problem shows up again.

Related

LateInitializationError: Field '_children#51042623' has not been initialized

[![LateInitializationError: Field '_children#51042623' has not been initialized][1]]
I'm having this problem when i add items to a List from page 2 to page 1
[1]: https://i.stack.imgur.com/LzmDY.png
I'm using SQLITE to create db for the list, If i run the app again it works normally.
How can i solve this problem? I searched on this website and i found one post but i tried to follow the step and i still can't solve.
code of page 2
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:mood3/helper/AnotacaoHelper.dart';
import 'package:mood3/main.dart';
import 'package:mood3/model/Diario.dart';
import 'package:mood3/telas/RecebeDados.dart';
import 'package:path_provider/path_provider.dart';
import 'package:toast/toast.dart';
class Escrita extends StatefulWidget {
#override
State<Escrita> createState() => _EscritaState();
}
class _EscritaState extends State<Escrita> {
TextEditingController _controllerTitulo = TextEditingController();
TextEditingController _controllerTexto = TextEditingController();
var _db = AnotacaoHelper();
List<Diario> _diarioupdate = <Diario>[];
_recuperarDiario()async{
List diarioRecuperado = await _db.recuperarDiario();
List<Diario> diariotemporario = <Diario>[];
for ( var item in diarioRecuperado){
Diario diario = Diario.fromMap(item);
diariotemporario.add(diario);
}
setState((){
_diarioupdate = diariotemporario;
});
print("Lista anotacoes : "+ diarioRecuperado.toString() );
}
_salvarAnotacao() async {
String titulo = _controllerTitulo.text;
String texto = _controllerTexto.text;
Diario diario = Diario(titulo, texto, DateTime.now().toString());
int? resultado = await _db.salvarDiario(diario);
print("salvar anotacao: " + resultado.toString());
_controllerTitulo.clear();
_controllerTexto.clear();
_recuperarDiario();
}
#override
Widget build(BuildContext context) {
ToastContext().init(context);
GlobalKey<FormState>myFormKey=GlobalKey<FormState>();
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
key: myFormKey,
appBar: AppBar(
automaticallyImplyLeading: false,
title: InkWell(
child: Image.asset("icones/mood.jpg"),
onTap: ()=> Navigator.push(context, MaterialPageRoute(builder: (context) => TelaPrincipal())),
),
actions: [
IconButton(
icon: Image.asset("testeimagem/2.png"),
onPressed: (){
print("acao: chat");
},
),
IconButton(
icon: Icon(Icons.account_circle),
onPressed: (){
print("acao: account");
},
),
],
backgroundColor: Colors.black,
),
body: Center(
child: SingleChildScrollView(
child:Column(
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextField(
keyboardType: TextInputType.multiline,
controller: _controllerTitulo,
autofocus: true,
decoration: InputDecoration(
hintText: "Diary Title",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.blueGrey,
),
)),
Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextField(
keyboardType: TextInputType.multiline,
controller: _controllerTexto,
maxLines: null,
decoration: InputDecoration(
hintText: "Diary Text",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.blueGrey,
),
),
),
],
),),
),
floatingActionButton: SpeedDial(
icon: CupertinoIcons.pen,
backgroundColor: Colors.black,
overlayColor: Colors.black,
children: [
SpeedDialChild(
child: Icon(CupertinoIcons.arrow_left),
backgroundColor: Colors.white,
label: "Back",
onTap: () {
Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context) => RecebeDados() ));
}
),
SpeedDialChild(
child: Icon(CupertinoIcons.check_mark),
backgroundColor: Colors.white,
label: "Save",
onTap: () {
_salvarAnotacao();
Navigator.of(context,rootNavigator: true).pop();
Navigator.push(context, MaterialPageRoute(builder: (context) => RecebeDados() ));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text('Diary Saved')));
},
),
SpeedDialChild(
child: Icon(CupertinoIcons.add),
backgroundColor: Colors.white,
label: "Post",
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text('You Diary has been published successfully'),
));
Navigator.pop(context);
}
),
]
),
),);
}
}
code of page 1
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:line_icons/line_icons.dart';
import 'package:mood3/helper/AnotacaoHelper.dart';
import 'package:mood3/main.dart';
import 'package:mood3/model/Diario.dart';
import 'package:mood3/telas/Diary.dart';
import 'package:mood3/widget/DismissibleWidget.dart';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:mood3/telas/escrita.dart';
class RecebeDados extends StatefulWidget {
#override
State<RecebeDados> createState() => _RecebeDadosState();
}
class _RecebeDadosState extends State<RecebeDados> {
Map<String,dynamic> _ultimaTarefaRemovida = Map();
var _db = AnotacaoHelper();
List<Diario> _diarioupdate2 = <Diario>[];
_recuperarDiario()async{
List diarioRecuperado = await _db.recuperarDiario();
List<Diario> diariotemporario = <Diario>[];
for ( var item in diarioRecuperado){
Diario diario = Diario.fromMap(item);
diariotemporario.add(diario);
}
setState((){
_diarioupdate2 = diariotemporario;
});
print("Lista anotacoes : "+ diarioRecuperado.toString() );
print("Lista anotacoes : "+ _diarioupdate2.toString() );
print("Lista anotacoes : " + diariotemporario.toString());
}
#override
void initState() {
super.initState();
_recuperarDiario();
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
floatingActionButton: SpeedDial(
animatedIcon: AnimatedIcons.menu_close,
backgroundColor: Colors.black,
icon: CupertinoIcons.pencil,
overlayColor: Colors.black,
children: [
SpeedDialChild(
child: Icon(CupertinoIcons.arrow_left),
backgroundColor: Colors.white,
label: "Back",
onTap: () {
Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context) => TelaPrincipal() ));
},
),
SpeedDialChild(
child: Icon(CupertinoIcons.add),
backgroundColor: Colors.white,
label: "Add",
onTap: () {
Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context) => Escrita() ));
}
),
SpeedDialChild(
child: Icon(CupertinoIcons.delete),
backgroundColor: Colors.white,
label: "Remove",
onTap: () {
},
),
]
),
body: Column(
children: [
Expanded(child:
ListView.separated(
itemCount: _diarioupdate2.length,
separatorBuilder: (context,index)=> Divider(),
itemBuilder: (context,index){
final diario = _diarioupdate2[index];
return Card(
child: DismissibleWidget(
child: buildListTile(diario),
),
);
},
),
),
],
)
),
);
}
Widget buildListTile(Diario diario) => ListTile(
contentPadding: EdgeInsets.symmetric(
horizontal: 16, vertical: 16,
),
leading: CircleAvatar(
radius: 28,
backgroundImage: AssetImage("icones/m.png"),
),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(diario.titulo!,
style: TextStyle(
fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Text("${diario.data} - ${diario.mensagem}")
],
),
);
}

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");

How to keep disappearing Flutter Bottom Navigation and AppBar after navigating from subpages

I have a bottom Tab bar in my app for navigation and appbar, from the menu page after adding products in Cart screen there is Continue button when i pressed it take me to Login screen, there a normal login with and otp verification, now when i try to navigate back to menu screen after successfull otp verification, i see Tab bar disappeared and the App bar.
How i can fix this problem
Cart Screen
return Scaffold
....
row
...
Container showOrderConfirmationBtn(BuildContext context) {
return Container(
height: 50.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.transparent, style: BorderStyle.solid, width: 1.0),
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10.0),
),
child: FlatButton(
onPressed: () {
isLoggedIn == false
? Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginPage()))
: Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CarConfirmationCompletePage()));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
'Continue',
style: TextStyle(
color: Colors.white,
fontFamily: 'BuffetRegular',
fontSize: 13,
letterSpacing: 0.5),
),
],
),
)
],
),
),
);
}
}
Login Screen
return Scafold
....
GestureDetector(
onTap: () async {
final prefs =
await SharedPreferences.getInstance();
final customerData = LoginModel(
mobile: maskFormatter.getUnmaskedText());
final result = await loginServices
.loginCustomer(customerData);
final customerId = result['id'];
if (result['existsFlag'] == '1') {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
} else {
// Registering customer
// Registering customer device info
// and navigating the user to otpverification page
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => OtpVerification(
customerId: customerId)));
}
},
child: Container(
margin: const EdgeInsets.only(right: 20.0),
width: 40,
height: 40.0,
decoration: BoxDecoration(
color: Colors.green.shade300,
borderRadius: BorderRadius.circular(10.0),
),
child: Icon(Icons.arrow_forward_ios),
),
),
Otp Screen
return Scaffold
....
PinEntryTextField(
fieldWidth: 60.0,
showFieldAsBox: true,
onSubmit: (String pin) async {
final prefs = await SharedPreferences.getInstance();
// redirected to menu page
final optData =
OtpModel(customerId: widget.customerId, otp: pin);
final result = await loginServices.otpVerify(optData);
if (result['existsFlag'] == '1') {
// setting customer prefs
prefs.setBool('isLoggedIn', true);
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: null,
content: Text('неверный код подтверждения '),
);
},
); //end showDialog()
}
// ...............................
// showDialog(
// context: context,
// builder: (context) {
// return AlertDialog(
// title: Text("Pin"),
// content: Text('Pin entered is $pin'),
// );
// },
// ); //end showDialog()
// ...............................
}, // end onSubmit
),
Menu Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:get_it/get_it.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
// ... Constants
import '../constants.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Models
import '../models/cart_order.dart';
import '../models/menu_model.dart';
// ... API'S
import '../apis/api_response.dart';
import '../apis/menu-api.dart';
// ... Pages
import '../pages/menu_detail.dart';
class MenuPage extends StatefulWidget {
final Products pro;
MenuPage({Key key, this.pro}) : super(key: key);
#override
_MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
ProductApi get productsServices => GetIt.I<ProductApi>();
APIResponse<List<Products>> _apiResponse;
bool _isLoading = false;
void _fetchProducts() async {
setState(() {
_isLoading = true;
});
_apiResponse = await productsServices.getProductsList();
setState(() {
_isLoading = false;
});
}
hasDiscount(product) {
return product.hasDiscount == '1'
? product.priceAfter
: product.hasDiscount == '0'
? product.priceBefore
: product.priceAfter;
}
#override
void initState() {
_fetchProducts();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: ListView(
physics: PageScrollPhysics(),
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: kDefaultPadding, vertical: kDefaultPadding),
child: Text('Меню', style: kStyleHeaders),
),
SizedBox(
height: 10.0,
),
Builder(builder: (_) {
if (_isLoading) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(child: null),
);
}
if (_apiResponse.error) {
return Center(child: Text(_apiResponse.errorMessage));
}
if (_apiResponse.data.length == 0) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Center(
child: Text(
'No products has been found..!',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
fontFamily: 'BuffetBold',
color: Colors.black,
),
),
),
);
}
return GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: _apiResponse.data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.72,
mainAxisSpacing: 1.0,
crossAxisSpacing: 1.0,
),
itemBuilder: (context, index) {
var product = _apiResponse.data[index];
return CachedNetworkImage(
imageUrl: product.imageMedium,
imageBuilder: (context, imageProvider) => Column(
children: [
GestureDetector(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetail(
id: product.id,
title: product.title,
description: product.description,
structure: product.structure,
imageLarge: product.imageLarge,
weight: product.weight,
hasDiscount: product.hasDiscount,
priceBefore:
double.parse(product.priceBefore),
priceAfter:
double.parse(product.priceAfter),
isHit: product.isHit,
isNew: product.isNew,
isSpicy: product.isSpicy,
isRecommended: product.isRecommended,
isVegetarian: product.isVegetarian,
attributes: product.attributes),
),
),
child: Container(
alignment: Alignment(-1, 0.9),
child: (product.isNew == '1')
? Image.asset(
'assets/images/new.png',
width: 60.0,
)
: null,
height: 165.0,
width: 165.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
),
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 2.0,
spreadRadius: 0,
offset: Offset(0, 2))
],
),
),
),
Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 10.0),
child: Row(
children: [
Flexible(
child: Text(product.title,
style: kStyleTitle))
],
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
product.weight != null
? product.weight
: '',
style: kStyleWeight),
Text(
product.hasDiscount != '0'
? product.priceBefore
: '',
style: kStyleDiscount),
Container(
margin: EdgeInsets.symmetric(
horizontal: 3, vertical: 0),
height: 30.0,
width: 70.0,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0),
),
color: kPrimaryColor,
textColor: Colors.white,
padding:
EdgeInsets.symmetric(horizontal: 5.0),
onPressed: () {
// ... Todo
context.read<OrderNotify>().addOrder(
CartOrder(
product: product,
qty: 1,
price: hasDiscount(product)),
);
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(hasDiscount(product),
style: kStylePrice),
Icon(
FontAwesomeIcons.rubleSign,
size: 13.0,
color: Colors.white,
)
],
),
),
),
],
),
),
],
),
placeholder: (context, url) => Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation(Color(0xffB81F33)),
),
),
errorWidget: (context, url, error) => Icon(
Icons.error,
size: 40.0,
color: Theme.of(context).primaryColor,
),
);
},
);
}),
],
),
],
),
),
);
}
}
Main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ... API'S
import './apis/category-api.dart';
import './apis/menu-api.dart';
import './apis/promotion-api.dart';
import './apis/login-api.dart';
import './apis/ipaddress-api.dart';
import './apis/deviceinfo-api.dart';
import './apis/customer_deviceinfo-api.dart';
// Providers
import './providers/order_notify.dart';
import 'app.dart';
void setupLocator() {
GetIt.I.registerLazySingleton(() => PromotionApi());
GetIt.I.registerLazySingleton(() => CategoriesApi());
GetIt.I.registerLazySingleton(() => ProductApi());
GetIt.I.registerLazySingleton(() => LoginApi());
GetIt.I.registerLazySingleton(() => IPAddressInfo());
GetIt.I.registerLazySingleton(() => DeviceInfo());
GetIt.I.registerLazySingleton(() => CustomerDeviceInfoApi());
}
void setDeviceInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
DeviceInfo deviceServices = GetIt.I<DeviceInfo>();
IPAddressInfo ipServices = GetIt.I<IPAddressInfo>();
prefs.setString('ipAddress', await ipServices.getIPAddress());
prefs.setString('manufacturerModel', await deviceServices.getPhoneInfo());
prefs.setString('deviceVersion', await deviceServices.getPhoneVersion());
prefs.setString('os', await deviceServices.getOperatingSystem());
prefs.setString(
'screenResolution', await deviceServices.getScreenResolution());
prefs.setString('packageOrBundle', await deviceServices.getPackageName());
prefs.setString('appVersion', await deviceServices.getAppVersion());
prefs.setString('isPhysical',
await deviceServices.isPhysicalDevice() == true ? '1' : '0');
prefs.setBool('isLoggedIn', false);
}
void main() {
// ... setup shared prefrences
// ... todo
// ... get device informaton set shared prefrences
// ... todo
// ... Setuploacator
setupLocator();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (ctx) => OrderNotify(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
),
),
);
setDeviceInfo();
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isStartHomePage = false;
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 3), () {
// If the page has not jump over the jump page
if (!isStartHomePage) {
// Go Home and destroy the current page
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => App(),
),
(Route<dynamic> rout) => false);
isStartHomePage = true;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
'assets/images/stripes_min.jpg',
),
),
),
),
Positioned(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/Buffet_Logo_Trans_min.png',
width: 200.0,
height: 200.0,
),
],
),
),
),
],
),
);
}
}
main.screen
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// ... APP Helpers
import '../helpers/app_helper.dart';
// ... Pages
import '../pages/home_page.dart';
import '../pages/promotions_page.dart';
import '../pages/menu_page.dart';
import '../pages/more_page.dart';
import '../pages/orders_page.dart';
import '../pages/cart.dart';
// ... Providers
import '../providers/order_notify.dart';
// ... Widgets
import '../widgets/badge.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
// Current Index set to 0
int currentTabIndex = 0;
final List<Widget> pages = [
HomePage(
key: PageStorageKey('HomePage'),
),
PromotionsPage(
key: PageStorageKey('PromoPage'),
),
MenuPage(
key: PageStorageKey('MenuOage'),
),
OrdersPage(
key: PageStorageKey('Orderpage'),
),
MorePage(
key: PageStorageKey('Morepage'),
),
Cart(
key: PageStorageKey('CartPage'),
)
];
final PageStorageBucket bucket = PageStorageBucket();
// Current page
Widget currentPage;
void setTabIndex(index) {
setState(() {
currentTabIndex = index;
currentPage = pages[index];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
elevation: 0.0,
leading: InkWell(
onTap: () {
Helper.launchUrl('tel:88007073566');
},
child: Icon(
Icons.call,
color: Colors.black,
size: 25.0,
),
),
title: Text(
'BUFFET',
style: TextStyle(fontSize: 30.0, fontFamily: 'BuffetBold'),
),
centerTitle: true,
actions: [
Container(
margin: EdgeInsets.symmetric(horizontal: 0),
width: 60,
child: Badge(
color: Colors.green,
child: IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Cart()));
},
),
value: context.watch<OrderNotify>().items.length.toString(),
),
)
],
),
body: PageStorage(
child: pages[currentTabIndex],
bucket: bucket,
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setTabIndex(index);
},
currentIndex: currentTabIndex,
type: BottomNavigationBarType.fixed,
selectedItemColor: Theme.of(context).primaryColor,
selectedFontSize: 0,
unselectedFontSize: 0,
iconSize: 30,
elevation: 0,
backgroundColor: Colors.white,
selectedIconTheme: IconThemeData(size: 28),
unselectedItemColor: Theme.of(context).focusColor.withOpacity(1),
selectedLabelStyle:
Theme.of(context).textTheme.bodyText1.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
unselectedLabelStyle:
Theme.of(context).textTheme.button.merge(TextStyle(
fontSize: 12,
fontFamily: 'BuffetBold',
)),
showUnselectedLabels: true,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home_outlined,
),
label: 'Главная',
),
BottomNavigationBarItem(
icon: Icon(Icons.card_giftcard_outlined),
label: 'Акции',
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant),
label: 'Меню',
),
BottomNavigationBarItem(
icon: Icon(Icons.av_timer),
label: 'Заказы',
),
BottomNavigationBarItem(
icon: Icon(Icons.menu),
label: 'Еще',
)
],
),
);
}
}
App.dart
import 'package:flutter/material.dart';
// ... Constants
import 'constants.dart';
// ... Screens
import './screens/main_screen.dart';
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Buffet',
theme: ThemeData(
primaryColor: kPrimaryColor,
fontFamily: 'Buffet',
),
home: MainScreen(),
);
}
}
Your mistake is that you pushed MenuPage to stack in OtpScreen
Navigator.push(context,
MaterialPageRoute(builder: (context) => MenuPage()));
You should pop the otp page or navigate to MainScreen that contains your PageStorage

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

PhotoURL was called on null error in flutter [duplicate]

This question already has answers here:
What is a NoSuchMethod error and how do I fix it?
(2 answers)
Closed 2 years ago.
In my flutter project, i used CachedNetworkImageProvider, in which i passed photo url, but it is showing me an error, that it is called on null. Can anyone help me please? Check out line 158. If you think, there is nothing wrong in this part, and some other widget is causing the error, (that are made by me), then please tell me, i will provide you that. Please help me. I am new to this thing.
Here's the exception -
The getter 'photoUrl' was called on null.
Receiver: null
Tried calling: photoUrl
The relevant error-causing widget was:
Upload file:///C:/Users/Hp/AndroidStudioProjects/social_app/lib/pages/home.dart:117:11
Here's the code -
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:social_app/models/users.dart';
class Upload extends StatefulWidget {
final User currentUser;
Upload({this.currentUser});
#override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> {
File file;
handleTakePhoto() async {
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 960, maxHeight: 675);
// ImagePicker imagePicker;
// PickedFile pickedFile = await imagePicker.getImage(source: ImageSource.camera, maxHeight: 675, maxWidth: 960);
// File file = File(pickedFile.path);
setState(() {
this.file = file;
});
}
handleChooseFromGallery() async{
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
this.file = file;
});
// ImagePicker imagePicker;
// PickedFile pickedFile = await imagePicker.getImage(source: ImageSource.gallery);
// File file = File(pickedFile.path);
// setState(() {
// this.file = file;
// });
}
selectImage(parentContext) {
return showDialog(
context: parentContext,
builder: (context) {
return SimpleDialog(
title: Text('Create Post'),
children: <Widget>[
SimpleDialogOption(
child: Text('Click Photo'),
onPressed: handleTakePhoto,
),
SimpleDialogOption(
child: Text('Import from Gallery'),
onPressed: handleChooseFromGallery,
),
SimpleDialogOption(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
],
);
}
);
}
Container buildSplashScreen() {
return Container(
color: Colors.black54,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SvgPicture.asset('assets/images/upload.svg', height: 300.0,),
Padding(
padding: EdgeInsets.only(top: 40.0),
child: RaisedButton(
padding: EdgeInsets.all(10.0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
child: Text(
'Upload Image',
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
),
color: Colors.blueGrey[600],
onPressed: () => selectImage(context),
),
),
],
),
);
}
clearImage() {
setState(() {
file =null;
});
}
Scaffold buildUploadForm() {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white70,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black,),
onPressed: clearImage,
),
title: Center(
child: Text(
'Caption Post',
style: TextStyle(
color: Colors.black,
),
),
),
actions: [
FlatButton(
onPressed: () => print('Pressed'),
child: Text(
'Post',
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
],
),
body: ListView(
children: <Widget>[
Container(
height: 220.0,
width: MediaQuery.of(context).size.width * 0.8,
child: Center(
child: AspectRatio(
aspectRatio: 16/9,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(file),
),
),
),
),
),
),
Padding(
padding: EdgeInsets.only(top: 10.0),
),
ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(widget.currentUser.photoUrl),
),
title: Container(
width: 250.0,
child: TextField(
decoration: InputDecoration(
hintText: "Write a caption..",
border: InputBorder.none,
),
),
),
),
Divider(
),
ListTile(
leading: Icon(
Icons.pin_drop,
color: Colors.blue,
size: 36.0,
),
title: Container(
width: 250.0,
child: TextField(
decoration: InputDecoration(
hintText: 'Search a location...',
border: InputBorder.none,
),
),
),
),
Container(
width: 200.0,
height: 100.0,
alignment: Alignment.center,
child: RaisedButton.icon(
label: Text(
'Use current location...',
style: TextStyle(
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Colors.blue,
onPressed: () => print('Get user location'),
icon: Icon(
Icons.my_location,
color: Colors.white,
),
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return file == null ? SafeArea(
child: Scaffold(
backgroundColor: Colors.black45,
body: buildSplashScreen(),
),
) : buildUploadForm();
}
}
home page -
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:social_app/pages/activity_feed.dart';
import 'package:social_app/pages/create_account.dart';
import 'package:social_app/pages/profile.dart';
import 'package:social_app/pages/search.dart';
import 'package:social_app/pages/timeline.dart';
import 'package:social_app/pages/upload.dart';
import 'package:social_app/widgets/header.dart';
import 'package:social_app/models/users.dart';
final GoogleSignIn googleSignIn = GoogleSignIn();
final usersRef = FirebaseFirestore.instance.collection('users');
final DateTime timeStamp = DateTime.now();
User currentUser;
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isAuth = false;
PageController pageController;
int pageIndex=0;
#override
void initState(){
super.initState();
pageController = PageController(initialPage: 0);
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
},
onError: (error) {
print("Error in signing in : $error");
});
googleSignIn.signInSilently(suppressErrors: false).then((account){
handleSignIn(account);
}).catchError((error){
print("Error in signing in : $error");
});
}
handleSignIn(GoogleSignInAccount account) {
if (account != null) {
createUserInFirestore();
setState(() {
isAuth = true;
});
}
else {
setState(() {
isAuth = false;
});
}
}
createUserInFirestore() async{
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.doc(user.id).get();
if(!doc.exists) {
final username = await Navigator.push(context, MaterialPageRoute(builder: (context) => CreateAccount()));
usersRef.doc(user.id).set({
"id" : user.id,
"username" : username,
"photoUrl" : user.photoUrl,
"email" : user.email,
"displayName" : user.displayName,
"bio" : "",
"timeStamp" : timeStamp,
});
}
}
#override
void dispose() {
pageController.dispose();
super.dispose();
}
login() {
googleSignIn.signIn();
}
logout() {
googleSignIn.signOut();
}
onPageChanged(int pageIndex) {
setState(() {
this.pageIndex = pageIndex;
});
}
onTap(int pageIndex) {
pageController.animateToPage(
pageIndex,
duration: Duration(milliseconds: 250),
curve: Curves.easeInOut,
);
}
Scaffold buildAuthScreen(){
return Scaffold(
body: PageView(
children: <Widget>[
//Timeline(),
RaisedButton(
onPressed: logout,
child: Text('logout'),
),
Search(),
Upload(currentUser: currentUser),
ActivityFeed(),
Profile(),
],
controller: pageController,
onPageChanged: onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: CupertinoTabBar(
backgroundColor: Colors.black,
currentIndex: pageIndex,
onTap: onTap,
activeColor: Colors.white,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home_filled)),
BottomNavigationBarItem(icon: Icon(Icons.search)),
BottomNavigationBarItem(icon: Icon(Icons.add_box_outlined)),
BottomNavigationBarItem(icon: Icon(Icons.favorite_border)),
BottomNavigationBarItem(icon: Icon(Icons.account_circle)),
],
),
);
// return RaisedButton(
// onPressed: logout,
// child: Text('logout'),
// );
}
Scaffold buildUnauthScreen() {
return Scaffold(
appBar: header(context, titleText: 'Instagram'),
backgroundColor: Colors.black,
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Theme.of(context).primaryColor,
Colors.teal.withOpacity(1.0),
Colors.orange,
]
),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Technua',
style: GoogleFonts.gochiHand(
fontSize: 70.0,
color: Colors.white,
),
),
GestureDetector(
onTap: login,
child: Container(
height: 60.0,
width: 260.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/google_signin_button.png'),
fit: BoxFit.cover,
)
),
),
),
],
),
),
),
);
}
#override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : buildUnauthScreen();
}
}
You have created an optional named parameter currentUser in your StatefulWidget Upload. I think the user that you have passed in the Upload widget is null.
You have to check where are you calling the Upload widget from & then check whether the user is null or not.
However, if the currentUser is null, you can prevent the error by using null aware operator as follows:
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(
widget.currentUser?.photoUrl, // <-----
),
),
Your current user is null. You have to set a user in here:
final User currentUser;