Firebase Phone Auth failed to sign out flutter - firebase

I have tried all the methods to sign out from firebase auth. I am using Phone number auth in the Flutter app using Firebase but am unable to sign out the user. Every time I restart the app it leads me to the Home page but when I click the Logout button it takes me to the Login page.
What I want is a simple sign-out.
Authentication class
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:food_express/pages/login_signup/login.dart';
class Authentication{
Future<void> logOut(BuildContext context) async {
try {
await FirebaseAuth.instance.signOut().then((value) => {
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => Login()), (route) => false)
});
} catch (e) {
print(e); // TODO: show dialog with error
}
}
}
Profile Widget
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:food_express/constant/constant.dart';
import 'package:food_express/functions/Authentication.dart';
import 'package:food_express/pages/login_signup/login.dart';
import 'package:food_express/pages/order/history_order/history.dart';
import 'package:food_express/pages/order/order.dart';
import 'package:food_express/pages/profile/edit_profile.dart';
import 'package:page_transition/page_transition.dart';
import 'package:food_express/pages/profile/address.dart';
import 'package:food_express/pages/notification.dart';
import "../../constant/globals.dart" as global;
class Profile extends StatelessWidget {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
logoutDialogue() {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
// return object of type Dialog
return Dialog(
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
child: Container(
height: 130.0,
padding: EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"You sure want to logout?",
style: headingStyle,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
InkWell(
onTap: () {
logout(context);
},
child: Container(
width: (width / 3.5),
alignment: Alignment.center,
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
'Cancel',
style: buttonBlackTextStyle,
),
),
),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Login()));
},
child: Container(
width: (width / 3.5),
alignment: Alignment.center,
padding: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: primaryColor,
borderRadius: BorderRadius.circular(5.0),
),
child: Text(
'Log out',
style: wbuttonWhiteTextStyle,
),
),
),
],
),
],
),
),
);
},
);
}
return Scaffold(
backgroundColor: scaffoldBgColor,
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: whiteColor,
elevation: 0.0,
title: Text(
'Profile',
style: bigHeadingStyle,
),
),
body: ListView(
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: EditProfile()));
},
child: Container(
width: width,
padding: EdgeInsets.all(fixPadding),
color: whiteColor,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 70.0,
height: 70.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
image: DecorationImage(
image: NetworkImage(
"https://png.pngtree.com/png-clipart/20200224/original/pngtree-cartoon-color-simple-male-avatar-png-image_5230557.jpg"),
fit: BoxFit.cover,
),
),
),
widthSpace,
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
global.profile.Name.toString(),
style: headingStyle,
),
heightSpace,
Text(
global.profile.PhoneNumber.toString(),
style: lightGreyStyle,
),
],
),
],
),
Icon(
Icons.arrow_forward_ios,
size: 16.0,
color: Colors.grey.withOpacity(0.6),
),
],
),
),
),
Container(
margin: EdgeInsets.all(fixPadding),
padding: EdgeInsets.all(fixPadding),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(5.0),
boxShadow: <BoxShadow>[
BoxShadow(
blurRadius: 1.5,
spreadRadius: 1.5,
color: Colors.grey[200],
),
],
),
child: Column(
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: Notifications()));
},
child: getTile(
Icon(Icons.notifications,
color: Colors.grey.withOpacity(0.6)),
'Notifications'),
),
/* InkWell(
onTap: () {
Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: PaymentMethods()));
},
child: getTile(
Icon(Icons.payment, color: Colors.grey.withOpacity(0.6)),
'Payment Methods'),
),
*/
/*InkWell(
onTap: () {},
child: getTile(
Icon(Icons.local_activity,
color: Colors.grey.withOpacity(0.6)),
'My Vouchers'),
),
*/
InkWell(
onTap: () {},
child: getTile(
Icon(Icons.group_add,
color: Colors.grey.withOpacity(0.6)),
'Invite Friends'),
),
],
),
),
Container(
margin: EdgeInsets.all(fixPadding),
padding: EdgeInsets.all(fixPadding),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(5.0),
boxShadow: <BoxShadow>[
BoxShadow(
blurRadius: 1.5,
spreadRadius: 1.5,
color: Colors.grey[200],
),
],
),
child: Column(
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: Order()));
},
child: getTile(
Icon(Icons.history, color: Colors.grey.withOpacity(0.6)),
'Order History'),
),
InkWell(
onTap: () {},
child: getTile(
Icon(Icons.group, color: Colors.grey.withOpacity(0.6)),
'Become our partner'),
),
InkWell(
onTap: () {},
child: getTile(
Icon(Icons.headset_mic,
color: Colors.grey.withOpacity(0.6)),
'Support'),
),
InkWell(
onTap: () {},
child: getTile(
Icon(Icons.star_rate,
color: Colors.yellow.withOpacity(0.6)),
'Rate our App'),
),
],
),
),
Container(
margin: EdgeInsets.all(fixPadding),
padding: EdgeInsets.all(fixPadding),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(5.0),
boxShadow: <BoxShadow>[
BoxShadow(
blurRadius: 1.5,
spreadRadius: 1.5,
color: Colors.grey[200],
),
],
),
child: Column(
children: <Widget>[
InkWell(
onTap: logoutDialogue,
child: getTile(
Icon(Icons.exit_to_app,
color: Colors.grey.withOpacity(0.6)),
'Logout'),
),
],
),
),
],
),
);
}
getTile(Icon icon, String title) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 40.0,
width: 40.0,
alignment: Alignment.center,
child: icon,
),
widthSpace,
Text(
title,
style: listItemTitleStyle,
),
],
),
Icon(
Icons.arrow_forward_ios,
size: 16.0,
color: Colors.grey.withOpacity(0.6),
),
],
);
}
void logout(context) {
Authentication _auth = Authentication();
_auth.logOut(context);
// await FirebaseAuth.instance.signOut();
// Navigator.pop(context);
}
}

Check the current user already log or not when log out, and when you use then block, you don't need to use the await keyword.
Future<void> logOut(BuildContext context) async {
try {
final User firebaseUser = await FirebaseAuth.instance.currentUser;
if (firebaseUser != null) {
FirebaseAuth.instance.signOut().then((value) => {
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)
=> Login()), (route) => false)
});
}
} catch (e) {
print(e); // TODO: show dialog with error
}
}

Related

Rules in cloud firestore has a issue (Flutter) - permission denied

I am building a flutter eCommerce app. if I log in as a new user, with google, or sign up, the home page doesn't load the products... in console, It shows cloud firestore permission denied. then after I close and reopen the app, the page loads with products.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
the above rule is not working. but if I log in, the user logs in successfully, also the user details are added to the DB.
Login page
Error:
W/Firestore( 1298): (22.0.2) [Firestore]: Listen for
Query(target=Query(product order by
name);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient
permissions., cause=null}
HomePage
class _HomeoneState extends State<Homeone> {
final _key = GlobalKey<ScaffoldState>();
ProductServices _productServices = ProductServices();
List _gender = ['Current location', 'loc1', 'loc2'];
String _genderVal;
#override
Widget build(BuildContext context) {
final userProvider = Provider.of<UserProvider>(context);
final productProvider = Provider.of<ProductProvider>(context);
return Scaffold(
key: _key,
backgroundColor: white,
endDrawer: Drawer(
child: ListView(
children: <Widget>[
UserAccountsDrawerHeader(
decoration: BoxDecoration(color: red,
borderRadius: BorderRadius.only(bottomRight: Radius.circular(50),bottomLeft: Radius.circular(50)),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
'https://blogrope.com/wp-content/uploads/2013/03/happy_wallpaper_by_melaamory-d5n8m53.jpg')),
),
accountName: CustomText(
text: userProvider.userModel?.name ?? "username lading...",
color: black,
weight: FontWeight.bold,
size: 18,
),
accountEmail: CustomText(
text: userProvider.userModel?.email ?? "email loading...",
color: black,
),
),
ListTile(
onTap: () async{
await userProvider.getOrders();
changeScreen(context, OrdersScreen());
},
leading: Icon(Icons.bookmark_outlined,color: Colors.black,),
title: CustomText(text: "My orders"),
),
ListTile(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => MyHomePage()));
},
leading: Icon(Icons.exit_to_app_outlined,color: Colors.black,),
title: CustomText(text: "Log out"),
),
ListTile(
onTap: () {
userProvider.signOut();
},
leading: Icon(Icons.exit_to_app_outlined,color: Colors.black,),
title: CustomText(text: "Log out"),
),
ListTile(
onTap: () {
AuthService().signOutGoogle();
Navigator.push(
context, MaterialPageRoute(builder: (context) => Login()));
},
leading: Icon(Icons.add),
title: CustomText(text: "Log out for google"),
),
],
),
),
body:
SafeArea(
child: ListView(
physics: AlwaysScrollableScrollPhysics(),
children: <Widget>[
// Custom App bar
Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(5.0),
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Hi',style: TextStyle(color: Colors.black),)),
Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
userProvider.userModel?.name ?? "wait...",
),
),
Container(
margin: EdgeInsets.all(14),
child: Padding(
padding: const EdgeInsets.fromLTRB(200.0,0,0,0),
child: Align(
alignment: Alignment.topRight,
child: GestureDetector(
onTap: (){
changeScreen(context, CartScreen());
},
child: Icon(Icons.shopping_cart))),
),
),
],
),
),
Container(
margin: EdgeInsets.fromLTRB(280, 0, 0, 0),
child: GestureDetector(
onTap: () {
_key.currentState.openEndDrawer();
},
child: Icon(Icons.menu)),
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Align(
alignment: Alignment.topLeft,
child: Text(
'Delivering to',
style: TextStyle(
color: Colors.grey,
),
),
),
),
Container(
padding: EdgeInsets.all(8),
margin: EdgeInsets.all(4),
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent),
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.white,
),
child: DropdownButton(
hint: Text('Current location'),
dropdownColor: Colors.white,
value: _genderVal,
isExpanded: true,
onChanged: (value) {
setState(() {
_genderVal = value;
});
},
items: _gender.map((value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
),
),
],
),
// Search Text field
// Search(),
Container(
decoration: BoxDecoration(
color: white,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(24),
bottomLeft: Radius.circular(24))),
child: Padding(
padding: const EdgeInsets.only(
top: 5, left: 14, right: 14, bottom: 14),
child: Container(
decoration: BoxDecoration(
color: grey.withOpacity(0.2),
borderRadius: BorderRadius.circular(15),
),
child: ListTile(
leading: Icon(
Icons.search,
color: black,
),
title: TextField(
textInputAction: TextInputAction.search,
onSubmitted: (pattern)async{
await productProvider.search(productName: pattern);
changeScreen(context, ProductSearchScreen());
},
decoration: InputDecoration(
hintText: "Search...",
border: InputBorder.none,
),
),
),
),
),
),
// featured products
ListTile(
title: Text('Menu of the Day',
style: TextStyle(color: Colors.black, fontSize: 18),),
trailing: Text('View all', style: TextStyle(color: Colors.red),
),
),
FeaturedProducts(),
ListTile(
title: Text('Highly rated foods',
style: TextStyle(color: Colors.black, fontSize: 18),),
trailing: Text('View all', style: TextStyle(color: Colors.red),
),
),
FeaturedProductsone(),
// recent products
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(14.0),
child: Container(
alignment: Alignment.centerLeft,
child: new Text('Recent products')),
),
],
),
Column(
children: productProvider.products
.map((item) => GestureDetector(
child: ProductCard(
product: item,
),
))
.toList(),
),
],
),
),
);
}
}
Login
final userProvider = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body:userProvider.status == Status.Authenticating ? Loading() : Form(
key: _formKey,
child: ListView(
children: <Widget>[
Container(
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(30),
child: Center(
child: Text(
'Login',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w500,
),
),
),
),
Container(
child: Center(
child: Text(
'Add details to login',
style: TextStyle(
fontSize: 15,
),
),
),
),
Container(
padding: EdgeInsets.all(20),
child: TextFormField(
controller: _email,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
suffixIcon: Icon(Icons.email),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
hintText: 'Your Email',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
filled: true,
fillColor: Colors.grey[200],
),
validator: (value) {
if (value.isEmpty) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return 'Please make sure your email address is valid';
else
return null;
}
},
),
),
Container(
padding: EdgeInsets.all(20),
child: TextFormField(
controller: _password,
obscureText: true,
decoration: InputDecoration(
suffixIcon: Icon(Icons.vpn_key_sharp),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
hintText: 'Password',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
filled: true,
fillColor: Colors.grey[200],
),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
),
Container(
padding: EdgeInsets.all(40),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40.0),
),
color: Color(0xfffd44323),
child: Text('Login',
style: TextStyle(
fontSize: 20,
)),
textColor: Colors.white,
onPressed: () async {
// _loginUser(type: LoginType.email,email:_emailController.text, password:_passwordController.text,context: context);
if(_formKey.currentState.validate()){
if(!await userProvider.signIn(_email.text, _password.text))
_key.currentState.showSnackBar(SnackBar(content: Text("Failure")));
return;
}
changeScreenReplacement(context, HomePage());
},
),
),
InkWell(
child: Container(
child: Center(
child: Text(
'Forgot password',
style: TextStyle(
fontSize: 15,
),
),
),
),
onTap: (){
// Navigator.push(
// context, MaterialPageRoute(builder: (context) => Dashone()));
},
),
Container(
margin: EdgeInsets.all(35.0),
child: Center(
child: Text(
'or Login with ',
style: TextStyle(
fontSize: 15,
),
),
),
),
Container(
padding: EdgeInsets.all(5),
margin: EdgeInsets.all(20.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent),
borderRadius: BorderRadius.all(Radius.circular(34)),
color: Color(0xfff3680c1),
),
child: Center(
child: ListTile(
leading: SvgPicture.asset('assets/facebook.svg',
color: Colors.white),
title: Center(
child: Text(
'Login with facebook',
style: TextStyle(
color: Colors.white,
fontSize: 17,
),
)),
),
),
),
Container(
padding: EdgeInsets.all(5),
margin: EdgeInsets.all(20.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent),
borderRadius: BorderRadius.all(Radius.circular(34)),
color: Color(0xfffd44323),
),
child: Center(
child: InkWell(
child: ListTile(
leading: SvgPicture.asset(
'assets/google-plus.svg',
color: Colors.white,
height: 25.0,
width: 25.0,
),
title: Center(
child: InkWell(
child: Container(
child: Text(
'Login with Google',
style: TextStyle(
color: Colors.white,
fontSize: 17,
),
),
),
onTap: () async {
FirebaseAuth _auth = FirebaseAuth.instance;
User user = await AuthService().signInWithGoogle();
print(user);
if (user == null) {
_userServices.createUser({
"name": _auth.currentUser.displayName,
"photo": _auth.currentUser.photoURL,
"email": _auth.currentUser.email,
"uid": _auth.currentUser.uid,
"votes": votes,
"trips": trips,
"rating": rating,
});
// _userServices.createUser(
//
//
// );
// 5s over, navigate to a new page
Navigator.pushReplacement(
context, MaterialPageRoute(
builder: (context) => HomePage()));
}
},
),
)
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: Center(
child: Text(
'Don\'t have an Account?',
style: TextStyle(
fontSize: 15,
),
),
),
),
InkWell(
child: Container(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text(
'Sign up',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xfffd44323),
),
),
),
),
onTap: () {
changeScreen(context, SignUp());
},
),
],
),
],
),
),
);
}
}
After restaring the app

Firestore - Save Query Result

Good evening everyone, I have a problem with Firebase. Basically I'm creating a leaderboard and I have to find the 7 users with the most points, no problem on that one but I can't understand how to save the data of the 7 users to show them later in a Text widget.
This is the function i made :
Future<void> getLeaderboard() async {
return await FirebaseFirestore.instance
.collection("leaderboard")
.orderBy('Score', descending: true)
.limit(7)
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
print(doc["first_name"]);
}),
});
}
How do I save the Username and Score of all 7 users to reuse it later?
This is the Page Code :
import 'package:sizer/sizer.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:goodgoals_android/pages/home_page.dart';
import 'package:goodgoals_android/pages/profile_page.dart';
import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';
import 'package:goodgoals_android/services/authentication.dart';
class soloLeaderboardPage extends StatefulWidget {
soloLeaderboardPage({Key key, this.auth, this.userId, this.logoutCallback, this.home})
: super(key: key);
final BaseAuth auth;
final VoidCallback logoutCallback;
final String userId;
final HomePage home;
#override
State<StatefulWidget> createState() => new _soloLeaderboardPageState();
}
class _soloLeaderboardPageState extends State<soloLeaderboardPage> {
final _formKey = new GlobalKey<FormState>();
final databaseReference = FirebaseFirestore.instance;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
var _selectedTab = _SelectedTab.leaderboard;
var Nick = "";
#override
void initState() {
super.initState();
asyncMethod();
}
void asyncMethod() async {
await getLeaderboard();
}
void _handleIndexChanged(int i) {
setState(() {
_selectedTab = _SelectedTab.values[i];
print("Valore $i");
if (i == 0) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
}
else if (i == 3) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfilePage(),
));
}
else if (i == 2) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => soloLeaderboardPage(),
));
}
});
}
Future<void> getLeaderboard() async {
return await FirebaseFirestore.instance
.collection("leaderboard")
.orderBy('Score', descending: true)
.limit(7)
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
setState(() {
Nick = (doc["Score"]);
});
}),
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Stack(
children: <Widget>[
_showForm(),
]
),
);
}
Widget _showForm() {
return new Container(
padding: EdgeInsets.all(10.0),
child: new Form(
key: _formKey,
child: new ListView(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
children: <Widget>[
leaderbordSelector(),
showPodium1(),
showOtherPosition(),
bottomBarMimic(),
//bottomBarMimic(),
],
),
));
}
Widget bottomBarMimic() {
return Positioned(
width: 100.0.w,
bottom: 0,
left: 0,
child: Container(
color: Colors.white,
child: SalomonBottomBar(
currentIndex: _SelectedTab.values.indexOf(_selectedTab),
onTap: _handleIndexChanged,
items: [
SalomonBottomBarItem(
icon: Icon(Icons.home),
title: Text("Home"),
selectedColor: Colors.purple,
),
SalomonBottomBarItem(
icon: Icon(Icons.menu_book_sharp),
title: Text("Magazine"),
selectedColor: Colors.pink,
),
SalomonBottomBarItem(
icon: Icon(Icons.bar_chart),
title: Text("Leaderboard"),
selectedColor: Colors.orange,
),
SalomonBottomBarItem(
icon: Icon(Icons.person),
title: Text("Profile"),
selectedColor: Colors.teal,
),
],
)),
);
}
Widget leaderbordSelector() {
return new Padding(
padding: EdgeInsets.symmetric(vertical: 5.0.h, horizontal: 17.0.h),
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.person, color: Colors.blue),
onPressed: () {}
),
IconButton(
icon: Icon(Icons.people),
onPressed: () {}
),
],
),
);
}
Widget showPodium1() {
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: <Widget>[
Container(
height: 20.0.h,
width: 30.0.w,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Colors.black),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
child: Stack(
children: <Widget>[
Container(
width: 80.0.w,
height: 10.0.h,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fitHeight,
image: AssetImage('assets/images/no_image.png'),
)),
),
Container(
height: 10.0.h,
width: 10.0.w,
child:
new Image(
image: AssetImage(
"assets/images/medal_third.png"),
)),
Stack(
alignment: Alignment.center,
children: <Widget>[
Text("Test",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 20.0.sp),
textAlign: TextAlign.center,
),
new Align(alignment: Alignment.bottomCenter,
child: Text("Punti",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 15.0.sp),
),
),
],
),
]),
)],
),
Column(
children: <Widget>[
Container(
height: 20.0.h,
width: 30.0.w,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Colors.black),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
child: Stack(
children: <Widget>[
Container(
width: 80.0.w,
height: 10.0.h,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fitHeight,
image: AssetImage('assets/images/no_image.png'),
)),
),
Container(
height: 10.0.h,
width: 10.0.w,
child:
new Image(
image: AssetImage(
"assets/images/medal_first.png"),
)),
Stack(
alignment: Alignment.center,
children: <Widget>[
Text("Test",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 20.0.sp),
textAlign: TextAlign.center,
),
new Align(alignment: Alignment.bottomCenter,
child: Text("Punti",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 15.0.sp),
),
),
],
),
],
)
),
],
),
Column(
children: <Widget>[
Container(
height: 20.0.h,
width: 30.0.w,
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
border: Border.all(color: Colors.black),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
child: Stack(
children: <Widget>[
Container(
width: 80.0.w,
height: 10.0.h,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fitHeight,
image: AssetImage('assets/images/no_image.png'),
)),
),
Container(
height: 10.0.h,
width: 10.0.w,
child:
new Image(
image: AssetImage(
"assets/images/medal_second.png"),
)),
Stack(
alignment: Alignment.center,
children: <Widget>[
Text(Nick,
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 20.0.sp),
textAlign: TextAlign.center,
),
new Align(alignment: Alignment.bottomCenter,
child: Text("Punti",
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
color: const Color(0xFF3A404C),
fontSize: 15.0.sp),
),
),
],
),
],
)
),
],
),
],
));
}
Widget showOtherPosition() {
return Card(
margin: EdgeInsets.symmetric(vertical: 4.0.h),
elevation: 0,
color: Colors.transparent,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 0.5.h),
child: Column(
children: <Widget>[
Wrap(
spacing: 5.0,
children: <Widget>[
Container(
height: 10.0.h,
width: 500.0.w,
color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
),
),
SizedBox(height: 20),
Container(
height: 10.0.h,
width: 500.0.w,
color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
),
),
SizedBox(height: 20),
Container(
height: 10.0.h,
width: 500.0.w,
color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(
Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
)),
SizedBox(height: 20),
Container(
height: 10.0.h,
width: 500.0.w,
color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFFFFFFF),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 7,
offset: Offset(0, 3),
)
]
),
),
),
],
)
],
)),
);
}
}
enum _SelectedTab {home, magazine, leaderboard, ProfilePage}
The simplest way is use setState.
var firstName = "";
Future<void> getLeaderboard() async {
return await FirebaseFirestore.instance
.collection("leaderboard")
.orderBy('Score', descending: true)
.limit(7)
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
setState(() {
firstName = (doc["first_name"]);
});
}),
});
}
And change NICK HERE to firstName.
Text("NICK HERE",...),

Flutter: Couldn't reach the class properties in Build Widget with Firebase connection

Everytime when I try to use loggegInUser property it returns null please help me to solve this issue
getCurrent() methods works properly and prints user email and password but I can not acces this variables in Build Widget.
class _ProfilePageState extends State<ProfilePage> {
final _auth = FirebaseAuth.instance;
FirebaseUser loggedInUser;
String uid;
var url;
var userProfilePhotoUrl;
int currentPageIndex = 2;
CircularBottomNavigationController _navigationController =
new CircularBottomNavigationController(2);
List<TabItem> tabItems = List.of([
new TabItem(Icons.home, "Home", Colors.blue,
labelStyle: TextStyle(fontWeight: FontWeight.normal)),
new TabItem(Icons.add, "Let's Party", Colors.orange,
labelStyle: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
new TabItem(Icons.person, "Reports", Colors.red),
]);
#override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
uid = user.uid;
print(loggedInUser.email);
print(uid);
}
} catch (e) {
print(e);
}
}
void changePage(int index) {
setState(() {
currentPageIndex = index;
});
}
Future<FirebaseImage> getFirebaseProfilPhoto() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
uid = user.uid;
print(loggedInUser.email);
print(uid);
return FirebaseImage(
'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png');
}
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
setState(() {
getCurrentUser();
});
return Scaffold(
appBar: AppBar(
title: Text('furkanakguun'),
),
body: Builder(
builder: (context) => Container(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.black,
backgroundImage: FirebaseImage(
'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png'),
// FirebaseImage(
// 'gs://homeparty-68792.appspot.com/user_profile_images/$uid.png'),
//backgroundImage: Image.network(userProfilePhotoUrl),
radius: 100,
),
Padding(
padding: EdgeInsets.only(top: 60.0),
child: IconButton(
icon: Icon(
FontAwesomeIcons.camera,
size: 30.0,
),
focusColor: Colors.white,
color: Colors.deepPurple,
onPressed: () {
print('asd');
Navigator.pushNamed(context, 'image_uploader');
},
),
),
],
),
Divider(),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.person),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text('Furkan Akgün',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
),
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.location_on),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text('Ankara',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
),
],
),
),
),
],
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Card(
color: Colors.grey[900],
margin: EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(Icons.rate_review),
),
Card(
color: Colors.grey[900],
margin:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 7.0),
child: Container(
child: SmoothStarRating(
spacing: 2.0,
allowHalfRating: true,
starCount: 5,
rating: 4.5,
size: 20,
color: Colors.yellow,
borderColor: Colors.white,
isReadOnly: true,
)),
),
],
),
SizedBox(
height: 20.0,
),
SizedBox(
height: 40.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
color: Colors.deepPurple[900],
onPressed: () {
//uploadPic(context);
},
elevation: 4.0,
splashColor: Colors.blueGrey,
child: Text(
'Edit',
style: TextStyle(color: Colors.white, fontSize: 16.0),
),
),
],
)
],
),
),
),
bottomNavigationBar: CircularBottomNavigation(
tabItems,
barBackgroundColor: Colors.deepPurple[900],
controller: _navigationController,
selectedCallback: (int selectedPos) {
if (selectedPos == 0) {
Navigator.pushNamed(context, 'dashboard_screen');
}
if (selectedPos == 2) {
Navigator.pushNamed(context, 'user_profile');
}
},
),
);
}
}
enter image description here
ERROR TYPE
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid)
My guess is that the error comes from this code in your build method:
FirebaseImage('gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png')
This is because the UI may be built before the user sign-in is completed.
To prevent this from happening you need to handle the fact that the user may not be signed in, in your build code too, for example by skipping the rendering of their profile image:
backgroundImage: loggedInUser != null ?
FirebaseImage('gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png') :
Text("Loading...")

A build function returned null ,The relevant error-causing widget was : StreamBuilder<EzuserData>

Hi so I was doing an app like uber but I got an error of this. I'm new in using flutter. Before this, I can run app this normally but suddenly I got this error this morning.
This is my code. Can someone help me?
this is the error
A build function returned null.
The offending widget is: StreamBuilder
To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".
import 'package:ezbin3/Aboutus.dart';
import 'package:ezbin3/SCREENS/home/map.dart';
import 'package:ezbin3/SCREENS/home/map2.dart';
import 'package:ezbin3/SERVICES/auth.dart';
import 'package:ezbin3/activity.dart';
import 'package:ezbin3/models/user.dart';
import 'package:ezbin3/profile.dart';
import 'package:ezbin3/settings.dart';
import 'package:flutter/material.dart';
import 'package:ezbin3/SERVICES/database.dart';
import 'package:provider/provider.dart';
import 'package:ezbin3/models/ezuser.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<EzuserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
EzuserData userData = snapshot.data;
return StreamProvider<List<Ezuser>>.value(
value: DatabaseService().userz,
child: Scaffold(
drawer: Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
decoration: BoxDecoration(
gradient: LinearGradient(colors: <Color>[
Colors.lightGreen,
Colors.green
])),
child: Container(
child: Column(
children: <Widget>[
Material(
borderRadius:
BorderRadius.all(Radius.circular(50.0)),
elevation: 10,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Image.asset(
'image/ezbin2.png',
width: 80,
height: 80,
),
),
),
SizedBox(height: 10),
Text(
userData.name,
style: TextStyle(
color: Colors.white, fontSize: 20.0),
),
],
)),
),
//PROFILE PAGE
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.lightGreenAccent,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfilePage())),
child: Container(
height: 50,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.person),
Padding(
padding:
const EdgeInsets.all(8.0),
child: Text('Profile',
style: TextStyle(
fontSize: 16.0))),
],
),
Icon(Icons.arrow_right)
],
),
)),
)),
//ACTIVITY PAGE
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.lightGreenAccent,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ActivityPage())),
child: Container(
height: 50,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.description),
Padding(
padding:
const EdgeInsets.all(8.0),
child: Text('Activity',
style: TextStyle(
fontSize: 16.0))),
],
),
Icon(Icons.arrow_right)
],
),
)),
)),
//SETTING PAGE
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.lightGreenAccent,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SettingPage())),
child: Container(
height: 50,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.settings),
Padding(
padding:
const EdgeInsets.all(8.0),
child: Text('Settings',
style: TextStyle(
fontSize: 16.0))),
],
),
Icon(Icons.arrow_right)
],
),
)),
)),
//ABOUT US PAGE
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.lightGreenAccent,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AboutusPage())),
child: Container(
height: 50,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.info_outline),
Padding(
padding:
const EdgeInsets.all(8.0),
child: Text('About Us',
style: TextStyle(
fontSize: 16.0))),
],
),
Icon(Icons.arrow_right)
],
),
)),
)),
//LOG OUT
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.lightGreenAccent,
onTap: () async {
await _auth.signOut();
print('logout');
},
child: Container(
height: 50,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.lock),
Padding(
padding:
const EdgeInsets.all(8.0),
child: Text('Log Out',
style: TextStyle(
fontSize: 16.0))),
],
),
Icon(Icons.arrow_right)
],
),
)),
))
],
),
),
backgroundColor: Colors.green[50],
appBar: AppBar(
title: Text('EZBIN'),
backgroundColor: Colors.green[400],
elevation: 0.0,
actions: <Widget>[],
),
body: //HomeGoogle(),
MapSample(),
),
);
}
});
}
}
If anything happens please let me know. Thank you
Let's take a look at the error message
A build function returned null. The offending widget is: StreamBuilder
That means, that somewhere in your program a StreamBuilder (or its build method) is not returning a Widget, but null.
Now let's take a look at your code.
return StreamBuilder<EzuserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
EzuserData userData = snapshot.data;
return StreamProvider<List<Ezuser>>.value(
...
);
}
});
}
With the error and the simplified code in mind, where could you not return a Widget, but instead no value at all? Hint: What happens, if snapshot.hasData is not true?

Flutter: How Can I Get URL From Firebase Storage In Firestore

I want to upload the image to firebase storage in want to store the download URL in the firestore. I have the code that I have bellowed! but the problem is whenever I try to upload an image the image upload successfully but the URL did not save in the firestore. It's returns me Null.
How can I store the URL to firestore?
class NewFund extends StatefulWidget {
NewFund();
#override
_NewFundState createState() => _NewFundState();
}
class _NewFundState extends State<NewFund> {
final GlobalKey<FormState> _fundFormKey = GlobalKey<FormState>();
String userID, postName, postDetails, postImgUrl;
String filepath = '${DateTime.now()}.png';
File _imageFile;
StorageUploadTask _uploadTask;
final FirebaseStorage _storage =
FirebaseStorage(storageBucket: 'gs://i-donate-402dd.appspot.com');
getUserName(userId) {
this.userID = userID;
}
getPostName(postName) {
this.postName = postName;
}
getTaskDetails(postDetails) {
this.postDetails = postDetails;
}
getImageUrl(postImgUrl) {
this.postImgUrl = postImgUrl;
}
int _myPostType = 0;
String postVal;
void _handleTaskType(int value) {
setState(() {
_myPostType = value;
switch (_myPostType) {
case 1:
postVal = 'food';
break;
case 2:
postVal = 'health';
break;
case 3:
postVal = 'money';
break;
case 4:
postVal = 'clothes';
break;
case 5:
postVal = 'education';
break;
}
});
}
Widget radioButton(bool isSelected) => Container(
width: 16.0,
height: 16.0,
padding: EdgeInsets.all(2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(width: 2.0, color: Colors.black)),
child: isSelected
? Container(
width: double.infinity,
height: double.infinity,
decoration:
BoxDecoration(shape: BoxShape.circle, color: Colors.black),
)
: Container(),
);
Widget horizontalLine() => Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Container(
width: ScreenUtil.getInstance().setWidth(120),
height: 1.0,
color: Colors.black26.withOpacity(.2),
),
);
createFund() {
var authP = Provider.of<AuthP>(context);
var uid = authP.uid;
DocumentReference ds =
Firestore.instance.collection('posts').document(postName);
Map<String, dynamic> posts = {
"userID": uid,
"postName": postName,
"postDetails": postDetails,
"postCat": postVal,
"postImgUrl": postImgUrl,
};
setState(() {
_saveImage();
});
ds.setData(posts).whenComplete(() {
print("posts updated");
});
}
Future<String> _saveImage() async {
_uploadTask = _storage.ref().child(filepath).putFile(_imageFile);
var downURL = await (await _uploadTask.onComplete).ref.getDownloadURL();
postImgUrl = downURL.toString();
print('LINK URL : $postImgUrl');
return postImgUrl;
}
Future<void> _pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
setState(() {
_imageFile = selected;
});
}
#override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance =
ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
return Form(
key: _fundFormKey,
child: Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomPadding: true,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 20.0),
child: Image.asset("assets/imagemain.jpg"),
),
Expanded(
child: Container(),
),
Image.asset("assets/image_02.png")
],
),
SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(left: 28.0, right: 28.0, top: 60.0),
child: Column(
children: <Widget>[
SizedBox(
height: ScreenUtil.getInstance().setHeight(20),
),
Container(
width: double.infinity,
height: ScreenUtil.getInstance().setHeight(850),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 15.0),
blurRadius: 15.0),
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, -10.0),
blurRadius: 10.0),
]),
child: Padding(
padding:
EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Raise Fund",
style: TextStyle(
fontSize:
ScreenUtil.getInstance().setSp(45),
fontFamily: "Poppins-Bold",
letterSpacing: .6)),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Title",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize:
ScreenUtil.getInstance().setSp(26))),
TextField(
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(),
onChanged: (String name) {
getPostName(name);
},
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Fund Details",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize:
ScreenUtil.getInstance().setSp(26))),
TextField(
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(),
onChanged: (String postDetails) {
getTaskDetails(postDetails);
},
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Select Fund Type",
style: TextStyle(
fontFamily: "Poppins-Bold",
fontSize:
ScreenUtil.getInstance().setSp(26))),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
value: 1,
groupValue: _myPostType,
onChanged: _handleTaskType,
activeColor: Color(0xff4158ba),
),
Text(
'Food',
style: TextStyle(fontSize: 16.0),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
value: 2,
groupValue: _myPostType,
onChanged: _handleTaskType,
activeColor: Color(0xfffb537f),
),
Text(
'Health',
style: TextStyle(
fontSize: 16.0,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
value: 3,
groupValue: _myPostType,
onChanged: _handleTaskType,
activeColor: Color(0xff4caf50),
),
Text(
'Money',
style: TextStyle(fontSize: 16.0),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
value: 4,
groupValue: _myPostType,
onChanged: _handleTaskType,
activeColor: Color(0xff9962d0),
),
Text(
'Clothes',
style: TextStyle(fontSize: 16.0),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Radio(
value: 5,
groupValue: _myPostType,
onChanged: _handleTaskType,
activeColor: Color(0xff0dc8f5),
),
Text(
'Education',
style: TextStyle(fontSize: 16.0),
),
],
),
],
),
],
),
),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(20),
),
RaisedButton(
onPressed: () {
_pickImage(ImageSource.gallery);
},
child: Text('Upload Document'),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(20),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
child: Container(
width: ScreenUtil.getInstance().setWidth(330),
height: ScreenUtil.getInstance().setHeight(100),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xFF17ead9),
Color(0xFF6078ea)
]),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0)
]),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
createFund();
},
child: Center(
child: Text("Raise",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins-Bold",
fontSize: 18,
letterSpacing: 1.0)),
),
),
),
),
)
],
),
],
),
),
)
],
),
),
);
}
}
here is how you can implement it
final StorageReference storageReference =
FirebaseStorage.instance.ref().child('images/$name');
StorageUploadTask uploadTask = storageReference.putData(asset);
final StreamSubscription<StorageTaskEvent> streamSubscription =
uploadTask.events.listen((event) {
// You can use this to notify yourself or your user in any kind of way.
// For example: you could use the uploadTask.events stream in a StreamBuilder instead
// to show your user what the current status is. In that case, you would not need to cancel any
// subscription as StreamBuilder handles this automatically.
});
await uploadTask.onComplete;
streamSubscription.cancel();
//get your ref url
String docUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
//docUrl is your url as a string
Firestore.instance
.collection('collectiion')
.document()
.updateData({"url": docUrl});

Resources