PhotoURL was called on null error in flutter [duplicate] - flutter

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;

Related

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

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.

Flutter default profile picture for signup with u8intlist

The code below is my signup code, it has everything that I need but I got a problem with the default image. I made the connection with firebase but now I need to insert a default picture if the person doesn't chose a profile picture. What is the best way to tackle this?
I use de imagepicker to pick a picture from your own gallery, that is used in a async function called selectimage()
Then the async signup function is the function where the authmethods().signUpUser takes place. In this function it will then say that _image is null and that I can't use the ! operator.
import 'dart:typed_data';
import 'package:event_app/pages/Login_Page.dart';
import 'package:event_app/resources/auth_methods.dart';
import 'package:event_app/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:image_picker/image_picker.dart';
import '../utils/colors.dart';
import '../widgets/text_field_input.dart';
import '../widgets/password_field_input.dart';
import 'Verify_Email_Page.dart';
class SignupPage extends StatefulWidget {
const SignupPage({Key? key}) : super(key: key);
#override
_SignupPageState createState() => _SignupPageState();
}
class _SignupPageState extends State<SignupPage> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _usernameController = TextEditingController();
bool _isLoading = false;
Uint8List? _image;
#override
void dispose() {
super.dispose();
_emailController.dispose();
_passwordController.dispose();
_usernameController.dispose();
}
void selectImage() async {
Uint8List im = await pickImage(ImageSource.gallery);
setState(() {
_image = im;
});
}
void signUpUser() async {
setState(() {
_isLoading = true;
});
String res = await AuthMethods().signUpUser(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
file: _image!);
if (res == "Success") {
setState(() {
_isLoading = false;
});
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const VerifyEmailPage()));
} else {
setState(() {
_isLoading = false;
});
showSnackBar(res, context);
}
}
void navigateToLogin() {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const LoginPage()));
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 32),
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
child: Container(),
flex: 2,
),
SvgPicture.asset(
'assets/ic_instagram.svg',
color: textColor,
height: 64,
),
const SizedBox(
height: 64,
),
Stack(
children: [
_image != null
? CircleAvatar(
radius: 64,
backgroundImage: MemoryImage(_image!),
backgroundColor: Colors.grey,
)
: const CircleAvatar(
radius: 64,
backgroundImage: NetworkImage(
'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png'),
backgroundColor: Colors.grey,
),
Positioned(
bottom: -10,
left: 80,
child: IconButton(
onPressed: selectImage,
icon: const Icon(Icons.add_a_photo)))
],
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your username',
textInputType: TextInputType.text,
textEditingController: _usernameController,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your email',
textInputType: TextInputType.emailAddress,
textEditingController: _emailController,
),
const SizedBox(
height: 24,
),
PasswordFieldInput(
hintText: 'Enter your password',
textInputType: TextInputType.text,
textEditingController: _passwordController,
),
const SizedBox(
height: 24,
),
InkWell(
child: Container(
child: !_isLoading
? const Text('Sign up')
: const Center(
child: CircularProgressIndicator(
color: textColor,
),
),
width: double.infinity,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: const ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
),
color: accentColor,
),
),
onTap: signUpUser,
),
SizedBox(
height: 12,
),
Flexible(
child: Container(),
flex: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: const Text("Already have an account?"),
padding: const EdgeInsets.symmetric(vertical: 8),
),
GestureDetector(
onTap: navigateToLogin,
child: Container(
child: const Text(
"Login.",
style: TextStyle(fontWeight: FontWeight.bold),
),
padding: const EdgeInsets.symmetric(vertical: 8),
),
)
],
),
],
),
)),
);
}
}
What if you change the selectImage function from async to sync function to prevent api call before _image is set.
void selectImage(){
pickImage(ImageSource.gallery).then(
(im){
setState(() {
_image = im;
});
});
}

Field '_image' has not been initialized in flutter

I wastrying image upload in flutter using imagepicker. While I was choose image the image cant display in one container. I was no error in error console. But the error was"Field '_image' has not been initialized. I am confused in flutter. Please he me guys
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
File? _image;
final picker = ImagePicker();
TextEditingController namecontroller = TextEditingController();
Future chooseimage() async {
var pickedImage = await picker.pickImage(source: ImageSource.gallery);
setState(() {
//_image = File(pickedImage!.path);
_image = File(pickedImage!.path);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Upload Image"),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: chooseimage,
child: Text("Select Image"),
style: ElevatedButton.styleFrom(primary: Colors.green),
),
TextField(
controller: namecontroller,
decoration: InputDecoration(label: Text("Name")),
),
SizedBox(
height: 30.0,
),
ElevatedButton(
onPressed: () {},
child: Text("Upload"),
style: ElevatedButton.styleFrom(primary: Colors.blue),
),
Container(
child: _image == null
? Text('No Image Select')
: Image.file(_image!),
),
],
),
),
),
);
}
}
///You can take a reference through this code hope this will work for you. Thanks
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:traveling/Provider/EmployeeProvider/EmployeeProfileProvider.dart';
import 'package:traveling/helpers/AppColors.dart';
///To get the crop value creating a class
enum AppState {
free,
picked,
cropped,
}
class EmployeeProfile extends StatefulWidget {
final bool leadingIcon;
final number;
final cardName;
EmployeeProfile(
{Key? key, required this.leadingIcon, this.number, this.cardName})
: super(key: key);
#override
_EmployeeProfileState createState() => _EmployeeProfileState();
}
class _EmployeeProfileState extends State<EmployeeProfile>
with TickerProviderStateMixin {
EmployeeProfileProvider? _provider;
///controller widget used in Spinkit plugin to show loading process
animationControllerField(){
AnimationController animationController =AnimationController(
vsync: this, duration: const Duration(milliseconds: 900));
}
bool? visible;
double? _width;
File? _image;
var url;
late AppState state;
final picker = ImagePicker();
///pop-up to choose camera gallery while uploading image
Future<void> _showChoiceDialog(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
"Choose option",
style: TextStyle(color: AppColors.hotelListDarkBlue),
),
content: SingleChildScrollView(
child: ListBody(
children: [
Divider(
height: 1,
color: AppColors.baseLightBlueColor,
),
ListTile(
onTap: () {
Navigator.pop(context, _pickImage(ImageSource.gallery,context));
},
title: Text(
"Gallery",
style: TextStyle(color: AppColors.hotelListDarkBlue),
),
leading: Icon(
Icons.account_box,
color: AppColors.baseLightBlueColor,
),
),
Divider(
height: 1,
color: AppColors.baseLightBlueColor,
),
ListTile(
onTap: () {
Navigator.pop(context, _pickImage(ImageSource.camera,context));
},
title: Text(
"Camera",
style: TextStyle(color: AppColors.hotelListDarkBlue,),
),
leading: Icon(
Icons.camera,
color: AppColors.baseLightBlueColor,
),
),
],
),
),
);
});
}
///crop image selecting by the user
Future<Null> _cropImage() async {
File? croppedFile = await ImageCropper.cropImage(
sourcePath: _image!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: AppColors.baseLightBlueColor,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
_image = croppedFile;
setState(() {
state = AppState.cropped;
});
///to get upload image
url = await _provider!.setUserUpdatedImageInfo(_image!, );
setState(() {
///to set the image
_provider!.currentLoggedInUser!.image = url;
});
}
}
///icon change while user edit image
Widget _buildButtonIcon() {
if (state == AppState.free)
return Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
);
else if (state == AppState.picked)
return Icon(Icons.crop,color: AppColors.popUpBlueColor,
size: 20,);
else if (state == AppState.cropped)
return Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
);
else
return Container();
}
#override
void initState() {
// TODO: implement initState
super.initState();
print("initState called");
state = AppState.free;
_provider = EmployeeProfileProvider();
_provider!.getUserInfo();
}
///this widget is the main widget and it is used for building a UI in the app.
#override
Widget build(BuildContext context) {
_width = MediaQuery.of(context).size.width;
return ChangeNotifierProvider<EmployeeProfileProvider?>(
create: (context) => _provider!,
child: Consumer<EmployeeProfileProvider?>(
builder: (context, provider, child) {
return provider!.currentLoggedInUser==null?
Material(
color: AppColors.white,
child: Center(
child:
SpinKitCubeGrid(
color: AppColors.baseLightBlueColor,
size: 50.0,
controller:animationControllerField()
),
),
):Container(
width: _width!,
color: AppColors.white,
child: Stack(
children: [
Column(
children: [
Material(
color: AppColors.baseLightBlueColor,
elevation: 15,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.only(bottomRight: Radius.circular(30)),
),
child: Container(
height: 180,
decoration: BoxDecoration(
color: AppColors.baseLightBlueColor,
// AppColors.blue,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(30)),
),
),
),
],
),
Positioned(
top: 80,
child:
Stack(
children: [
Container(
height: 150,
width: _width,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CachedNetworkImage(
filterQuality: FilterQuality.high,
maxHeightDiskCache: 100,
fit: BoxFit.cover,
imageUrl: provider.currentLoggedInUser!.image.toString(),
imageBuilder: (context, imageProvider) => Container(
height: 120,
width: 120,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: imageProvider, fit: BoxFit.cover),
border: Border.all(
color: AppColors.white, width: 2.0),
),
),
placeholder: (context, url) =>
const CircularProgressIndicator(),
errorWidget: (context, url, error) => Container(
height: 120,
width: 120,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
image:DecorationImage(
fit: BoxFit.cover,
image: AssetImage('assets/managerPicture.jpeg')),
border: Border.all(
color: AppColors.white, width: 2.0),
),
),
fadeOutDuration: const Duration(seconds: 1),
fadeInDuration: const Duration(seconds: 3),
),
],
),
),
Positioned(
top: 60,
right: 0,
left: 100,
bottom: 0,
child: GestureDetector(
onTap: () {
if (state == AppState.free)
_showChoiceDialog(context);
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) _showChoiceDialog(context);
},
child: Container(
height: 10,
width: _width,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Container(
height: 35,
width: 35,
decoration: BoxDecoration(
color:
AppColors.profiePicBackground,
borderRadius:
BorderRadius.circular(60),
),
child: ClipRRect(
borderRadius:
BorderRadius.circular(60.0),
child: _buildButtonIcon(),
/*Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
),*/
),
),
],
),
),
),
)
],
)
),
Positioned(
top: 40,
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 8, right: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
widget.leadingIcon == true
? Align(
alignment: Alignment.topLeft,
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(
MdiIcons.arrowLeft,
color: Colors.white,
)),
)
: Container(),
],
),
)),
],
),
);
}));
}
///ImageSource: Camera and Gallery.
Future<Null> _pickImage(ImageSource source,context) async {
final pickedImage = await ImagePicker().pickImage(source: source);
_image = pickedImage != null ? File(pickedImage.path) : null;
if (_image != null) {
setState(() {
state = AppState.picked;
});
}
}
}
class EmployeeProfileProvider extends ChangeNotifier {
late bool _isInfoEditable;
FirebaseFirestore? fireStoreInstance;
EmployeeProfileModel? _userData;
// EmployeeMyExpenseReport ? _employeeMyExpenseReport;
///to update the employee profile image
Future<String?> setUserUpdatedImageInfo(File _image, ) async {
var data= await EmployeeServices.getInstance().uploadImageToFirebase(_image, );
notifyListeners();
return data;
}
///to update Personal details of employee
EmployeeProfileModel? get getUploadedImage => _userData;
#override
void dispose() {
//print("Provider disposed called");
super.dispose();
}
//upload employee image on firebase
String ?url;
Future <String?>uploadImageToFirebase(File _image) async {
User? currentUser = FirebaseAuth.instance.currentUser;
String fileName = basename(_image.path);
firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
.ref().child('uploads')
.child('/$fileName');
final metadata = firebase_storage.SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'picked-file-path': fileName});
firebase_storage.UploadTask uploadTask;
uploadTask = ref.putFile(io.File(_image.path), metadata);
//String ?url;
await uploadTask.whenComplete(() async {
url = await uploadTask.snapshot.ref.getDownloadURL();
});
Future.value(uploadTask)
.then((value) => {
print("Upload file path ${value.ref.fullPath}"),
FirebaseFirestore.instance.collection(FirestoreCollections.employees).doc(currentUser!.uid).update({'image': '$url'}),
})
.onError((error, stackTrace) =>
{
print("Upload file path error ${error.toString()} ")}
);
return url;
}
}

page is not going to home screen after signing in using flutter

I am still a beginner in flutter so I don't have much knowledge about it , so the problem is that I am unable to enter app after signing up application is still showing sign up page even after signing in with google . so I have created an application where I need to signin and get inside the app it was working before adding support for google to take user info and now it is not going inside the home screen.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:concord/models/user.dart';
import 'package:concord/pages/create_account_page.dart';
import 'package:concord/pages/music_page.dart';
import 'package:concord/pages/profile_page.dart';
import 'package:concord/pages/search_page.dart';
import 'package:concord/pages/timeline_page.dart';
import 'package:concord/pages/upload_page.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
final GoogleSignIn gSignIn = GoogleSignIn();
final usersReference = FirebaseFirestore.instance.collection("users");
final DateTime timestamp = DateTime.now();
User currentUser;
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isSignedIn = false;
PageController pageController;
int getPageIndex = 0;
final _formKey = GlobalKey<FormState>();
void initState(){
//SystemChrome.setEnabledSystemUIOverlays([]);
super.initState();
pageController = PageController();
gSignIn.onCurrentUserChanged.listen((gSignInAccount) {
controlSignIn(gSignInAccount);
}, onError: (gError){
print("Error Message" + gError);
});
gSignIn.signInSilently(suppressErrors: false).then((gSignInAccount){
controlSignIn(gSignInAccount);
}).catchError((gError){
print("Error Message" + gError);
});
}
controlSignIn(GoogleSignInAccount signInAccount) async {
if (signInAccount != null)
{
await saveUserInfoToFireStore();
setState(() {
isSignedIn = true;
});
} else {
isSignedIn = false;
}
}
saveUserInfoToFireStore() async {
final GoogleSignInAccount gCurrentUser = gSignIn.currentUser;
DocumentSnapshot documentSnapshot = await usersReference.doc(gCurrentUser.id).get();
if(!documentSnapshot.exists){
final username = await Navigator.push(context,MaterialPageRoute(builder: (context) => CreateAccountPage()));
usersReference.doc(gCurrentUser.id).set({
"id": gCurrentUser.id,
"profileName": gCurrentUser.displayName,
"username": username,
"url": gCurrentUser.photoUrl,
"email": gCurrentUser.email,
"bio": "",
"timestamp": timestamp,
});
documentSnapshot = await usersReference.doc(gCurrentUser.id).get();
}
currentUser = User.fromDocument(documentSnapshot);
}
void dispose(){
pageController.dispose();
super.dispose();
}
loginUser(){
gSignIn.signIn();
}
logoutUser(){
gSignIn.signOut();
}
whenPageChanges(int pageIndex){
setState(() {
this.getPageIndex = pageIndex;
});
}
onTapChangePage(int pageIndex){
pageController.animateToPage( pageIndex, duration: Duration(milliseconds: 400), curve: Curves.bounceInOut);
}
Scaffold buildHomeScreen() {
return Scaffold(
body: PageView(
children : <Widget>[
TimeLinePage(),
SearchPage(),
MusicPage(),
UploadPage(),
ProfilePage(),
],
controller: pageController,
onPageChanged: whenPageChanges,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: Container(
padding: EdgeInsets.all(55.0),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
child: CupertinoTabBar(
currentIndex: getPageIndex,
onTap: onTapChangePage,
backgroundColor: Theme.of(context).accentColor,
activeColor: Colors.blue,
inactiveColor: Colors.blueGrey,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home)),
BottomNavigationBarItem(icon: Icon(Icons.search)),
BottomNavigationBarItem(icon: Icon(Icons.music_note,)),
BottomNavigationBarItem(icon: Icon(Icons.add_circle_outline_outlined)),
BottomNavigationBarItem(icon: Icon(Icons.person)),
],
),
),
),
);
//return ElevatedButton.icon(onPressed: logoutUser, icon: Icon(Icons.close), label: Text("Sign Out"));
}
#override
Widget build(BuildContext context) {
final mq = MediaQuery.of(context);
final greetings = Container(
alignment: Alignment.topLeft,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(15.0, 110.0, 0.0, 0.0),
child: Text(
'Its nice to meet you.',
style: TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
),
),
Container(
padding: EdgeInsets.fromLTRB(15.0, 250.0, 0.0, 0.0),
child: Text(
'Lets get in.',
style: TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),
),
),
],
),
);
final logo = Image.asset(
"assets/icons/concord_white.png",
height: mq.size.height / 4,
fit: BoxFit.contain,
);
final googleButton = Container(
height: 40.0,
color: Colors.transparent,
child: GestureDetector(
onTap: loginUser,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.white, style: BorderStyle.solid, width: 1.0),
color: Colors.transparent,
borderRadius: BorderRadius.circular(20.0)),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: ImageIcon(AssetImage('assets/icons/google_white.png')),
),
SizedBox(width: 10.0),
Center(
child: Text(
"Sign in with Google",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontFamily: 'Montserrat'),
),
),
],
),
),
),
);
Scaffold buildSignInScreen() {
return Scaffold(
body: Container(
key: _formKey,
padding: EdgeInsets.only(top: 35.0, left: 20.0, right: 20.0),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomRight,
end: Alignment.topLeft,
colors: [
Color.fromRGBO(49, 57, 125, 1.0),
Color.fromRGBO(137, 205, 174, 1.0),
],
),
),
alignment: Alignment.topCenter,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
greetings,
SizedBox(height: 20.0),
logo,
SizedBox(height: 20.0),
googleButton,
SizedBox(height: 20.0),
],
),
),
),
);
}
if (isSignedIn) {
return buildHomeScreen();
} else {
return buildSignInScreen();
}
}
}

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