Firestore - Save Query Result - firebase

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",...),

Related

Flutter - Strange white background from a expanded with widget

How can i get rid of this strange white background? I want to use weather widget in my app and i want it to be above MyGridView with buttons. I tried to do it with expanded but im always getting white background and my widget. I would like to use my weather widget as normal widget (like others) and be able to apply padding in home_screen.dart etc.
home_screen.dart
Widget build(BuildContext context) {
Color _iconColor = Colors.white.withOpacity(0.1);
double Size = MediaQuery.of(context).size.width;
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Color(0xff362a19),
Color(0xff101011),
Color(0xff301119)
])),
child: Scaffold(
appBar: CustomAppBar(),
backgroundColor: Colors.transparent,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
//IDEALNE https://github.com/Matt-rempel/flutter-weather-app/tree/master/assets/icons
Padding(
padding: EdgeInsets.only(top: 10, left: 25),
child: Text(
'${greeting()}',
style: TextStyle(
fontFamily: 'Helvetica Bold',
fontSize: 32,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 10, left: 25),
child: Text(
'Zarządzaj swoimi urządzeniami',
style: TextStyle(
fontFamily: 'Helvetica Bold',
fontSize: 16,
color: Colors.grey,
fontWeight: FontWeight.w600),
),
),
Padding(
padding: EdgeInsets.only(top: 20, left: 25),
),
Expanded(
child: CurrentWeatherPage(locations, context), //<--------------------------- HERE
),
Expanded(
child: MyGridView(),
),
],
//
),
bottomNavigationBar: Container(
padding: const EdgeInsets.only(bottom: 18.0),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(30.0),
),
child: BottomAppBar(
elevation: 0,
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
icon: Icon(
Icons.home,
color: _iconColor,
size: 28,
),
onPressed: null),
IconButton(
icon: Icon(
Icons.tv,
color: _iconColor,
size: 28,
),
onPressed: () {
setState(() {
_iconColor = Color(0xffc5073f);
});
}),
//
IconButton(
icon: Icon(
Icons.notifications,
color: _iconColor,
size: 28,
),
onPressed: null),
IconButton(
icon: Icon(
Icons.settings,
color: _iconColor,
size: 28,
),
onPressed: null),
],
),
),
),
//
) //
),
);
}
current_weather.dart
import 'package:firebaseauthproject/models/location.dart';
import 'package:firebaseauthproject/models/weather.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'extensions.dart';
class CurrentWeatherPage extends StatefulWidget {
final List<Location> locations;
final BuildContext context;
const CurrentWeatherPage(this.locations, this.context);
#override
_CurrentWeatherPageState createState() =>
_CurrentWeatherPageState(this.locations, this.context);
}
class _CurrentWeatherPageState extends State<CurrentWeatherPage> {
final List<Location> locations;
final Location location;
final BuildContext context;
_CurrentWeatherPageState(List<Location> locations, BuildContext context)
: this.locations = locations,
this.context = context,
this.location = locations[0];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),
);
}
}
Widget currentWeatherViews(
List<Location> locations, Location location, BuildContext context) {
Weather _weather;
return FutureBuilder(
builder: (context, snapshot) {
if (snapshot.hasData) {
_weather = snapshot.data;
if (_weather == null) {
return Text("Error getting weather");
} else {
return Column(children: [
weatherBox(_weather),
]);
}
} else {
return Center(child: CircularProgressIndicator());
}
},
future: getCurrentWeather(location),
);
}
Widget weatherBox(Weather _weather) {
return Stack(children: [
Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration: BoxDecoration(
color: Colors.indigoAccent,
borderRadius: BorderRadius.all(Radius.circular(20))),
),
ClipPath(
clipper: Clipper(),
child: Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration: BoxDecoration(
color: Colors.indigoAccent[400],
borderRadius: BorderRadius.all(Radius.circular(20))))),
Container(
padding: const EdgeInsets.all(15.0),
margin: const EdgeInsets.all(15.0),
height: 160.0,
decoration:
BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20))),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
getWeatherIcon(_weather.icon),
Container(
margin: const EdgeInsets.all(5.0),
child: Text(
"${_weather.description.capitalizeFirstOfEach}",
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 16,
color: Colors.white),
)),
Container(
margin: const EdgeInsets.all(5.0),
child: Text(
"H:${_weather.high.toInt()}° L:${_weather.low.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
color: Colors.white),
)),
])),
Column(children: <Widget>[
Container(
child: Text(
"${_weather.temp.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 60,
color: Colors.white),
)),
Container(
margin: const EdgeInsets.all(0),
child: Text(
"Feels like ${_weather.feelsLike.toInt()}°",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 13,
color: Colors.white),
)),
])
],
),
)
]);
}
Image getWeatherIcon(String _icon) {
String path = 'assets/weather/';
String imageExtension = ".png";
return Image.asset(
path + _icon + imageExtension,
width: 70,
height: 70,
);
}
class Clipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
Path path = Path();
path.moveTo(0, size.height - 20);
path.quadraticBezierTo((size.width / 6) * 1, (size.height / 2) + 15,
(size.width / 3) * 1, size.height - 30);
path.quadraticBezierTo((size.width / 2) * 1, (size.height + 0),
(size.width / 3) * 2, (size.height / 4) * 3);
path.quadraticBezierTo((size.width / 6) * 5, (size.height / 2) - 20,
size.width, size.height - 60);
path.lineTo(size.width, size.height - 60);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
path.close();
return path;
}
#override
bool shouldReclip(Clipper oldClipper) => false;
}
Future getCurrentWeather(Location location) async {
Weather weather;
String city = location.city;
String apiKey = "0e97f1773e9ed9e93d3f99a91d14344f";
var url =
"https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";
final response = await http.get(url);
if (response.statusCode == 200) {
weather = Weather.fromJson(jsonDecode(response.body));
}
return weather;
}
If you put two Expanded widgets in a Column, it will try to take equal amount space. If you want to get rid of that white space change your code from this...
Expanded(
child: CurrentWeatherPage(locations, context),
),
Expanded(
child: MyGridView(),
),
to this....
Flexible(
fit: FlexFit.tight,
child: CurrentWeatherPage(locations, context),
),
Expanded(
child: MyGridView(),
),
or if you want the two widgets share equal space in column change your code from this..
body: Column(
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),
To this..
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
currentWeatherViews(this.locations, this.location, this.context)
],
),

Firebase Failed assertion: line 380 pos 10: 'data != null'

import 'package:flutter/material.dart';
import 'package:flutter_myapp/AllWidgets/Divider.dart';
import 'package:flutter_myapp/AllWidgets/progressDialog.dart';
import 'package:flutter_myapp/Assistants/requestAssistant.dart';
import 'package:flutter_myapp/DataHandler/appData.dart';
import 'package:flutter_myapp/Models/address.dart';
import 'package:flutter_myapp/Models/placePredictions.dart';
import 'package:flutter_myapp/configMaps.dart';
import 'package:provider/provider.dart';
class SearchScreen extends StatefulWidget {
#override
_SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen>
{
TextEditingController pickUpTextEditingController = TextEditingController();
TextEditingController dropOffTextEditingController = TextEditingController();
List<PlacePredictions> placePredictionList = [];
#override
Widget build(BuildContext context)
{
String placeAddress = Provider.of<AppData>(context).pickUpLocation.placeName ?? "";
pickUpTextEditingController.text = placeAddress;
return Scaffold(
body: Column(
children: [
Container(
height: 215.0,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black,
blurRadius: 6.0,
spreadRadius: 0.5,
offset: Offset(0.7, 0.7),
),
],
),
child: Padding(
padding: EdgeInsets.only(left: 25.0, top: 25.0, bottom: 20.0),
child: Column(
children: [
SizedBox(height: 5.0),
Stack(
children: [
GestureDetector(
onTap:()
{
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back
),
),
Center(
child: Text("Set Drop Off", style: TextStyle(fontSize: 18.0, fontFamily: "Brand Bold"),),
)
],
),
SizedBox(height: 16.0),
Row(
children: [
Image.asset("images/pickicon.png", height: 16.0, width: 16.0,),
SizedBox(width: 18.0,),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadius.circular(5.0),
),
child: Padding(
padding: EdgeInsets.all(3.0),
child: TextField(
controller: pickUpTextEditingController,
decoration: InputDecoration(
hintText: "PickUp Location",
fillColor: Colors.grey[400],
filled: true,
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.only(left: 11.0, top: 8.0, bottom: 8.0),
),
),
),
),
),
],
),
SizedBox(height: 10.0),
Row(
children: [
Image.asset("images/desticon.png", height: 16.0, width: 16.0,),
SizedBox(width: 18.0,),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadius.circular(5.0),
),
child: Padding(
padding: EdgeInsets.all(3.0),
child: TextField(
onChanged: (val)
{
findPlace(val);
},
controller: dropOffTextEditingController,
decoration: InputDecoration(
hintText: "Where to? ",
fillColor: Colors.grey[400],
filled: true,
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.only(left: 11.0, top: 8.0, bottom: 8.0),
),
),
),
),
),
],
),
],
),
),
),
//tile for predictions
SizedBox(height: 10.0,),
(placePredictionList.length > 0)
?Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListView.separated(
padding: EdgeInsets.all(0.0),
itemBuilder: (context, index)
{
return PredictionTile(placePredictions: placePredictionList[index],);
},
separatorBuilder: (BuildContext context, int index) => DividerWidget(),
itemCount: placePredictionList.length,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
),
)
:Container(),
],
),
);
}
void findPlace(String placeName) async
{
if(placeName.length > 1)
{
String autoCompleteUrl = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$placeName&key=$mapKey&sessiontoken=1234567890&components=country:us";
var res = await RequestAssistant.getRequest(autoCompleteUrl);
if(res == "failed")
{
return;
}
//print("Places Predictions Response :: ");
//print(res);
if(res["status"] == "OK")
{
var predictions = res["predictions"];
var placeList = (predictions as List).map((e) => PlacePredictions.fromJson(e)).toList();
setState(() {
placePredictionList = placeList;
});
}
}
}
}
class PredictionTile extends StatelessWidget
{
final PlacePredictions placePredictions;
PredictionTile({Key key,this.placePredictions}) : super(key: key);
#override
Widget build(BuildContext context)
{
return FlatButton(
padding: EdgeInsets.all(0.0),
onPressed: ()
{
getPlaceAddressDetails(placePredictions.place_id, context);
},
child: Container(
child: Column(
children: [
SizedBox(width: 10.0,),
Row(
children: [
Icon(Icons.add_location),
SizedBox(width: 14.0,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 8.0,),
Text(placePredictions.main_text, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 16.0),),
SizedBox(height: 2.0,),
Text(placePredictions.secondary_text, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12.0, color: Colors.grey),),
SizedBox(height: 8.0,),
],
),
),
],
),
SizedBox(width: 10.0,),
],
),
),
);
}
void getPlaceAddressDetails(String placeId, context) async
{
showDialog(
context: context,
builder: (BuildContext context) => ProgressDialog(message: "Setting Drop off, Please wait....",),
);
String placeDetailsUrl = "https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$mapKey";
var res = await RequestAssistant.getRequest(placeDetailsUrl);
Navigator.pop(context);
if(res == "failed")
{
return;
}
if(res["status"] == "OK")
{
Address address = Address();
address.placeName = res["result"]["name"];
address.placeId = placeId;
address.latitude = res["result"]["geometry"]["location"]["lat"];
address.longitude = res["result"]["geometry"]["location"]["lng"];
Provider.of<AppData>(context, listen: false).updateDropOffLocationAddress(address);
print("This is Drop Off Location :: ");
print(address.placeName);
Navigator.pop(context, "obtainDirection");
}
}
}
Please help me, I can't understand what's wrong.
I keep getting this error.
Exception caught by widgets library:
The following assertion was thrown building PredictionTile(dirty): A
non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart': Failed assertion: line 380
pos 10: 'data != null'
The Text Widget cannot contain null data, the error relies in the following lines:
Text(placePredictions.main_text, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 16.0),),
Text(placePredictions.secondary_text, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12.0, color: Colors.grey),),
To fix it, we could change them to:
Text(placePredictions.main_text ?? 'n/a', overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 16.0),),
Text(placePredictions.secondary_text ?? 'n/a', overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12.0, color: Colors.grey),),
That replaces the null data with 'n/a'.

Firebase Phone Auth failed to sign out flutter

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
}
}

How to merge two collections in Firebase flutter application?

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,
),
),
),
],
),
),
),
),
),
],
),

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