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
Related
Below is the vehicle uploading details file code that uploads details on the firebase. It uploads city, vehicle type, and phone number. I wanted to search for vehicle in the specified city. So basically it matches the details of user. For example a person wants to book vehicle in city Lahore and vehicle type Car so this should search in database if anyone uploaded details matching the description and show it to the user.
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flash_chat/constants.dart';
import 'package:flash_chat/constraints/rounded_button.dart';
import 'package:flash_chat/screens/Home.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:image_picker/image_picker.dart';
class UploadingVehicle extends StatefulWidget {
static const id = 'uploading_vehicle';
#override
_UploadingVehicleState createState() => _UploadingVehicleState();
}
class _UploadingVehicleState extends State<UploadingVehicle> {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
bool showSpinner = false;
static String uCity;
String description;
String phoneNumber;
String uDropdownvalue = 'Hiace';
var vehicles = ['Car','Suzuki Bolan','Hiace'];
File _image1,_image2,_image3;
String id;
final Picker = ImagePicker();
_UploadingVehicleState();
_imgFromCamera() async {
final image = await Picker.pickImage(
source: ImageSource.camera, imageQuality: 50
);
setState(() {
_image1 = File(image.path);
});
}
_imgFromGallery(String id) async {
final image = await Picker.pickImage(
source: ImageSource.gallery, imageQuality: 50
);
if(id == 'A'){
setState(() {
_image1 = File(image.path);
});
}else if(id == 'B'){
setState(() {
_image2 = File(image.path);
});
}
else if(id == 'C'){
setState(() {
_image3 = File(image.path);
});
}
}
void _showPicker(context, String id) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Photo Library'),
onTap: () {
_imgFromGallery(id);
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.black, //change your color here
),
title: Text('Upload vehicle'.toUpperCase(),
style: TextStyle(color: Colors.black)),
backgroundColor: Colors.yellowAccent.shade700,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back)),
actions: [
Icon(Icons.person),
],
),
body: SafeArea(
child: Container(
child: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kRegisterTextFieldDecoration.copyWith(
prefixIcon: Icon(Icons.location_city,
color: Colors.black,
),
hintText: 'Enter City',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
autofocus: true,
onChanged: (value){
uCity = value;
},
),
),
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
keyboardType: TextInputType.number,
decoration: kRegisterTextFieldDecoration.copyWith(
prefixIcon: Icon(
Icons.phone,
color: Colors.black,
),
hintText: 'Enter Phone Number',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
focusColor: Colors.blue,
),
onChanged: (value){
phoneNumber = value;
},
),
),
SizedBox(
height: 40,
),
Row(
children: <Widget>[
Text(
'Select Vehicle:',
style: TextStyle(
color: Colors.blue,
fontSize: 15,
),),
SizedBox(
width: 20,
),
Center(
child: DropdownButton<String>(
value: uDropdownvalue,
elevation: 16,
dropdownColor: Colors.white,
icon: Icon(Icons.arrow_downward,
color: Colors.black,
),
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
underline: Container(
height: 1,
color: Colors.black,
),
items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
return DropdownMenuItem<String>(
value: vehicle,
child: Text(vehicle),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
uDropdownvalue = newValue;
});
},
),
),
],
),
SizedBox(
height: 20,
),
Text(
'Add Description:',
style: TextStyle(
color: Colors.blue,
fontSize: 18,
),
),
Expanded(
child: Container(
child: TextField(
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
)
),
),
style: TextStyle(
color: Colors.black,
),
onChanged: (value){
description=value;
},
),
),
),
Row(
children: [
Expanded(
child: buildGestureDetector(context,_image1),
),
Expanded(
child: buildGestureDetector(context,_image2),
),
Expanded(
child: buildGestureDetector(context,_image3),
),
],
),
Roundedbutton(
color: Colors.yellow,
title: 'Upload vehicle',
onPressed: () async {
setState(() {
showSpinner = true;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Details uploaded successfully')),
);
_firestore.collection('Uploading Vehicle Details').add({
'City': uCity,
'Vehicle': uDropdownvalue,
'Description' : description,
'Phone.No#' : phoneNumber,
});
Navigator.pushNamed(context, HomeScreen.id);
},
),
],
),
),
),
),
),
);
}
GestureDetector buildGestureDetector(BuildContext context, File _image) {
//GestureDetector({#required this._image});
//File _image;
return GestureDetector(
onTap: () {
_showPicker(context, 'A');
},
child: CircleAvatar(
radius: 53,
backgroundColor: Colors.black,
child: _image != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.file(
_image,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
),
)
: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
color: Colors.grey[800],
),
),
),
);
}
}
And below is the code for the user who wants to book vehicle in his city. So it should search in firebase if the required details are present in the firebase or not. If yes it should retrieve the details from the firebase and show it to the person who's looking for it.
import 'package:flash_chat/constants.dart';
import 'package:flash_chat/constraints/rounded_button.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flash_chat/screens/uploading_vehicle.dart';
class Booking extends StatefulWidget {
static const id = 'booking';
#override
_BookingState createState() => _BookingState();
}
class _BookingState extends State<Booking> {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
final UploadingVehicle uv = new UploadingVehicle();
bool showSpinner = false;
String city;
String dropdownvalue = 'Hiace';
var vehicles = ['Car','Suzuki Bolan','Hiace'];
Object get uCity => null;
Object get uDropdownvalue => null;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.black, //change your color here
),
title: Text('Book vehicle'.toUpperCase(),
style: TextStyle(color: Colors.black)),
backgroundColor: Colors.yellowAccent.shade700,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back)),
actions: [
Icon(Icons.person),
],
),
body: SafeArea(
child: Container(
child: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 40,
),
Material(
elevation: 18,
shadowColor: Colors.black,
child: TextField(
style: TextStyle(
color: Colors.black,
),
decoration: kRegisterTextFieldDecoration.copyWith(
hintText: 'Enter City',
fillColor: Colors.white,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
onChanged: (value){
city=value;
},
),
),
SizedBox(
height: 40,
),
Row(
children: <Widget>[
Text(
'Select Vehicle:',
style: TextStyle(
color: Colors.blue,
fontSize: 15,
),),
SizedBox(
width: 20,
),
Center(
child: DropdownButton<String>(
value: dropdownvalue,
elevation: 16,
dropdownColor: Colors.white,
icon: Icon(Icons.arrow_downward,
color: Colors.black,
),
style: TextStyle(
color: Colors.black,
fontSize: 15,
),
underline: Container(
height: 1,
color: Colors.black,
),
items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
return DropdownMenuItem<String>(
value: vehicle,
child: Text(vehicle),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
dropdownvalue = newValue;
});
},
),
),
],
),
Roundedbutton(
color: Colors.yellow,
title: 'Search for vehicle',
onPressed: () async {
setState(() {
showSpinner = true;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Searched')),
);
_firestore.collection('Booking Details').add({
'City': city,
'Vehicle': dropdownvalue,
});
Navigator.pushNamed(context, Booking.id);
},
),
Container(
color: Colors.white,
child: Text('Details matched',
style: TextStyle(
color: Colors.black,
fontSize: 30,
),
)
: Text(
'Details not matched',
style: TextStyle(
color: Colors.black,
fontSize: 30,
),),
),
],
),
),
),
),
),
);
}
}
How am I supposed to do this?
As far as I can tell from the massive amount of code you shared, this is the code that adds the vehicle details to the database:
_firestore.collection('Uploading Vehicle Details').add({
'City': uCity,
'Vehicle': uDropdownvalue,
'Description' : description,
'Phone.No#' : phoneNumber,
});
If you want to search that information, you can use a query such as this one:
_firestore.collection('Uploading Vehicle Details')
.where('City', isEqualTo: 'San Francisco')
.where('Vehicle', isEqualTo: 'Toyota RAV4')
.get()
.then(...);
If you want to show this in the UI, you'll want to use snapshots instead of get and wrap it in a StreamBuilder as shown in the documentation on listening to realtime changes.
I have created a chat application using flutter and store data in Firebase .Firebase contains two collections .One collection contains user details and another one collection contains user chats with other user.I want to merge two collection details .How to get other user details stored in user collections?
I have attached with screenshots.
Firebase collection
Flutter code
I have the same thing implemented in my Application. What I did is I use the Streambuilder widget twice, one to pull the chats, each and every chat contains a sender_id, which I then use the Id in the second Stream builder to pull user info.
Check the code below.This is all chats page:
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('MyChatHeads')
.doc(_onlineUserId)
.collection('Heads')
.orderBy('head_time', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Scaffold(
body: Center(
child: SpinKitThreeBounce(
color: Colors.black54,
size: 20.0,
),
),
);
} else {
if (snapshot.data.documents.length == 0) {
return Scaffold(
body: placeHolder(),
);
placeHolder();
} else {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => SearchUsersPage(
userId: _onlineUserId,
),
),
);
},
child: Icon(Icons.contacts_rounded),
foregroundColor: Colors.white,
backgroundColor: Color(0xff47c8b0),
),
body: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot myChatHeads = snapshot.data.documents[index];
return chatHeadItem(
index, myChatHeads, snapshot.data.documents.length);
},
),
);
}
}
},
);
}
The item in all chats page
Widget chatHeadItem(int index, DocumentSnapshot myChatHeads, int length) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.where('user_id', isEqualTo: myChatHeads['head_subject'])
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: SpinKitThreeBounce(
color: Colors.black54,
size: 20.0,
),
);
} else {
if (snapshot.data.documents.length == 0) {
return Container(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
),
child: Row(
children: [
CircleAvatar(
radius: 30,
backgroundColor: Colors.green,
child: CircleAvatar(
radius: 28,
backgroundColor: Colors.white,
child: Image(
height: 56,
width: 56,
image: AssetImage('assets/images/holder.png'),
fit: BoxFit.cover,
),
),
),
SizedBox(
width: 10,
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 10,
),
Text(
'User not found',
style: GoogleFonts.quicksand(
color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 16.0,
letterSpacing: .5,
),
),
//setCompanyName(myInterviews),
SizedBox(
height: 4.0,
),
InkWell(
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => ChatsEngagePage(
userId: _onlineUserId,
secondUserId: myChatHeads['head_subject'],
),
),
);
},
child: Text(
'${myChatHeads['head_last_message']}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.quicksand(
color: Colors.black87,
fontSize: 16.0,
letterSpacing: .5,
),
),
),
SizedBox(
height: 10,
),
],
),
),
],
),
),
);
} else {
DocumentSnapshot secondUserInfo = snapshot.data.documents[0];
return Container(
//color: Colors.green,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
),
child: Column(
children: [
index == 0
? SizedBox(
height: 6,
)
: SizedBox(
height: 0,
),
InkWell(
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => ChatsEngagePage(
userId: _onlineUserId,
secondUserId: myChatHeads['head_subject'],
userName: secondUserInfo['user_name'],
userImage: secondUserInfo['user_image'],
),
),
);
},
child: Row(
children: [
InkWell(
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (_) => PublicProfilePage(
userId: _onlineUserId,
secondUserId: secondUserInfo['user_id'],
),
),
);
},
child: CachedNetworkImage(
imageUrl: secondUserInfo['user_image'],
imageBuilder: (context, imageProvider) =>
CircleAvatar(
radius: 30,
backgroundColor: Colors.green,
child: CircleAvatar(
radius: 28,
backgroundColor: Colors.white,
backgroundImage: imageProvider,
),
),
placeholder: (context, url) => CircleAvatar(
radius: 30,
backgroundColor: Colors.green,
child: CircleAvatar(
radius: 28,
backgroundColor: Colors.white,
backgroundImage: AssetImage(
'assets/images/holder.png',
),
),
),
errorWidget: (context, url, error) =>
CircleAvatar(
radius: 30,
backgroundColor: Colors.green,
child: CircleAvatar(
radius: 28,
backgroundColor: Colors.white,
backgroundImage: AssetImage(
'assets/images/holder.png',
),
),
),
),
),
SizedBox(
width: 10,
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 10,
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
'${secondUserInfo['user_name']}',
style: GoogleFonts.quicksand(
color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 16.0,
letterSpacing: .5,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
timeAgoSinceDateEn(
DateTime.fromMillisecondsSinceEpoch(
myChatHeads['head_time'],
).toString(),
),
//postSnap['press_formatted_date'],
style: GoogleFonts.quicksand(
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.grey,
),
),
),
],
),
//setCompanyName(myInterviews),
SizedBox(
height: 4.0,
),
Text(
'${myChatHeads['head_last_message']}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.quicksand(
color: Colors.black87,
fontSize: 16.0,
letterSpacing: .5,
),
),
SizedBox(
height: 10,
),
],
),
),
],
),
),
index == length - 1
? Container()
: Divider(
//color: Colors.red,
),
index == length - 1
? SizedBox(
height: 4,
)
: SizedBox(
height: 0,
),
],
),
),
);
}
}
},
);
}
This is a single chat page:
body: Stack(
children: [
Container(
height: double.infinity,
width: double.infinity,
color: Colors.grey[100],
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Chats')
.doc(userId)
.collection(secondUserId)
.orderBy('message_time', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: SpinKitThreeBounce(
color: Colors.black54,
size: 20.0,
),
),
);
} else {
if (snapshot.data.documents.length == 0) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Container(
width: MediaQuery.of(context).size.width / 3,
child: Image(
image: AssetImage('assets/images/empty.png'),
width: double.infinity,
),
),
),
);
} else {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: ListView.builder(
shrinkWrap: true,
reverse: true,
// physics: NeverScrollableScrollPhysics(),
// primary: false,
padding: EdgeInsets.zero,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot myPresses =
snapshot.data.documents[index];
if (myPresses['message_owner'] == userId) {
return Padding(
padding: index == 0
? EdgeInsets.only(bottom: height + 26)
: EdgeInsets.only(bottom: 0),
child: Bubble(
margin: BubbleEdges.only(top: 10),
nip: BubbleNip.rightTop,
alignment: Alignment.topRight,
color: Colors.lightGreen[100],
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
myPresses['message_body'],
style: GoogleFonts.quicksand(
fontSize: 16,
color: Colors.black87,
),
),
Text(
timeAgoSinceDateEn(
DateTime.fromMillisecondsSinceEpoch(
myPresses['message_time'],
).toString(),
),
//postSnap['press_formatted_date'],
style: GoogleFonts.quicksand(
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.grey,
),
),
),
],
),
),
);
} else {
return Padding(
padding: index == 0
? EdgeInsets.only(bottom: height + 26)
: EdgeInsets.only(bottom: 0),
child: Bubble(
margin: BubbleEdges.only(top: 10),
alignment: Alignment.topLeft,
nip: BubbleNip.leftTop,
color: Color(0xffd4eaf5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
myPresses['message_body'],
style: GoogleFonts.quicksand(
fontSize: 16,
color: Colors.black87,
),
),
Text(
timeAgoSinceDateEn(
DateTime.fromMillisecondsSinceEpoch(
myPresses['message_time'],
).toString(),
),
//postSnap['press_formatted_date'],
style: GoogleFonts.quicksand(
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.grey,
),
),
),
],
),
),
);
}
},
),
);
}
}
},
),
),
Positioned(
bottom: 10.0,
left: 10.0,
right: 10.0,
child: MeasuredSize(
onChange: (Size size) {
setState(() {
print(size);
height = size.height;
});
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(0),
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.4),
spreadRadius: 2,
blurRadius: 3,
offset: Offset(0, 2), // changes position of shadow
),
],
),
//height: 58,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: TextFormField(
controller: textEditingController,
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
maxLength: 800,
maxLines: null,
style: GoogleFonts.quicksand(
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.black54,
letterSpacing: .5,
),
),
decoration: InputDecoration(
labelText: 'Message',
contentPadding: const EdgeInsets.symmetric(
horizontal: 0.0, vertical: 0.0),
errorStyle: TextStyle(color: Colors.brown),
),
onChanged: (val) {
setState(() => _message = val);
},
validator: (val) =>
val.length < 1 ? ('Too short') : null,
),
),
SizedBox(
width: 16,
),
InkWell(
onTap: () {
_submitMessage();
},
child: Padding(
padding:
const EdgeInsets.only(right: 8.0, bottom: 20),
child: Icon(
Icons.send_rounded,
color: Colors.green,
),
),
),
],
),
),
),
),
),
],
),
Error: Could not find the correct Provider above this SignUp Widget
To fix, please:
Ensure the Provider is an ancestor to this SignUp
Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Ensure the correct context is being used.
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
bool hidePass = true;
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating ? Loading() : Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left:20, right:20.0, top: 80),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image.asset(
'images/cart.png',
width: 120.0,
// height: 240.0,
)),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _email,
decoration: InputDecoration(
hintText: "Email",
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
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;
}
return null;
},
),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
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;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = false;
});
}),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: deepOrange,
elevation: 0.0,
child: MaterialButton(
onPressed: () async{
if(_formKey.currentState.validate()){
if(!await user.signUp(_name.text ,_email.text, _password.text))
_key.currentState.showSnackBar(SnackBar(content: Text("Sign up failed")));
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(color: deepOrange, fontSize: 16),
))),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Or sign up with", style: TextStyle(fontSize: 18,color: Colors.grey),),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
child: MaterialButton(
onPressed: () async{
if(!await user.signUpWithGoogle())
_key.currentState.showSnackBar(SnackBar(content: Text("Sign in failed")));
},
child: Image.asset("assets/google-48.png", width: 30,)
)),
),
],
),
),
],
)),
),
),
],
),
);
}
}
keep getting error what am I doing wrong
how to print value of field.
what I have tried :
print(documents[index].data['Likes.$usersId']);
actually I need this for toggle between icons.
thanks.
Update:
Widget build(BuildContext context) {
return Container(
child: StreamBuilder<QuerySnapshot>(
stream: UserManagement().getPostsStream(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
final List<DocumentSnapshot> documents = snapshot.data.documents;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (_, index) {
return Card(
elevation: 4,
child: Padding(
padding: EdgeInsets.only(left: 10.0, top: 10),
child: InkWell(
onTap: () => navigateToDetail(
documents[index],
documents[index].data["Userid"],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Row(
children: <Widget>[
Container(
width: 45,
height: 45,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
documents[index].data["User Pic"]),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(50.5)),
),
),
Padding(
padding: EdgeInsets.only(left: 15),
child: Text(
documents[index].data["Name"],
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18),
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 60, bottom: 10),
child: Text(
DateFormat.yMMMd().add_jm().format(
DateTime.parse(documents[index]
.data["Creation Time"]
.toDate()
.toString())),
style: TextStyle(
color: Colors.black38, fontSize: 12),
),
),
Flexible(
child: Padding(
padding: EdgeInsets.only(left: 75, right: 15),
child: Text(
documents[index].data["Description"],
style: TextStyle(fontSize: 16),
),
),
),
Padding(
padding: EdgeInsets.only(
left: 75, top: 15, bottom: 8),
child: Text(
documents.length.toString() +
"Files uploaded",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 14,
fontStyle: FontStyle.italic),
),
),
Divider(),
new Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
IconButton(
onPressed: () {
print(documents[index].data['Likes.$usersId']);
},
icon: documents[index].data['$usersId'] == true ? Icon(Icons.favorite,
color: Colors.redAccent,
size: 23.0) : Icon(Icons.favorite_border,
color: Colors.redAccent,
size: 23.0)
),
/*Text(documents[index].data['Likes'].length.toString()),*/
],
),
),
Expanded(
child: IconButton(
onPressed: () {
navigateToDetail(documents[index],
documents[index].data["Userid"],);
},
icon: Icon(
Icons.chat_bubble_outline,
color: Colors.blue,
size: 23.0,
),
),
),
Expanded(
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.near_me,
color: Colors.blue,
size: 23.0,
),
),
),
],
),
],
),
),
),
);
});
}
}),
);
}
This is to get Posts :
Stream<QuerySnapshot> getPostsStream() {
return Firestore.instance.collection("Posts").orderBy(
"Creation Time", descending: true).snapshots();
}
Change this:
print(documents[index].data['Likes.$usersId']);
into this:
print(documents[index].data['Likes'][usersId]);
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});