Display Cloud Firebase data? [closed] - firebase

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hey Does anyone know how I can Display this variable url from my Cloud Firebase?
It would be very nice if someone could do a example that would be massive! :)
class EditProfile extends StatefulWidget {
#override
_EditProfileState createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
FocusNode myFocusNode1 = new FocusNode();
FocusNode myFocusNode3 = new FocusNode();
final _formkey = GlobalKey<FormState>();
String _UserName ;
String _Email ;
String _URL;
File _image;
Future getImage(BuildContext context) async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
uploadPic(context);
});
}
Future<DocumentSnapshot> getUserInfo() async {
var firebaseUser = await FirebaseAuth.instance.currentUser;
return await FirebaseFirestore.instance.collection("SerX")
.doc(firebaseUser.uid)
.get();
}
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(
fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
_URL = downUrl.toString();
setState(() async {
print('Profile Picture uploaded');
var firebaseUser = await FirebaseAuth.instance.currentUser;
FirebaseFirestore.instance.collection("SerX").doc(firebaseUser.uid).update({"url" : downUrl});
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}
#override
void dispose() {
myFocusNode1 = FocusNode();
myFocusNode3 = FocusNode();
super.dispose();
}
#override
Widget build(BuildContext context) {
myFocusNode1.addListener(() {setState(() {
}); });
myFocusNode3.addListener(() {setState(() {
}); });
final user = Provider.of<Userf>(context);
return StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if(snapshot.hasData){
UserData userData = snapshot.data;
return Form(
key: _formkey,
child: Scaffold(
appBar: AppBar(
bottom: PreferredSize(
child: Container(
color: Colors.blue,
height: 4.0,
),
preferredSize: Size.fromHeight(0)),
backgroundColor: Colors.black,
leading: IconButton(icon: Icon(Icons.arrow_back ,color: Colors.blue,),onPressed: (){
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => HomeScreen()));
},),
title: Text('Profile', style: TextStyle(
color:Colors.white,
fontSize: 25,
fontWeight: FontWeight.bold,
fontFamily: 'Orbitron',
),
textAlign: TextAlign.center,
),
),
body: Container(
color: Colors.black,
child: ListView(
children: [
Stack(
children: [
Container(
margin: EdgeInsets.fromLTRB(140,45,0,0),
width: 130,
height: 130,
decoration: BoxDecoration(
border: Border.all(
width: 3,
color: Colors.blue,
),
boxShadow: [BoxShadow(
spreadRadius: 2, blurRadius: 10,
color: Colors.white.withOpacity(0.1),
offset: Offset(0,10),
),
],
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.cover,
image: (_image != null) ? FileImage(
_image)
: NetworkImage(_URL.toString()),
)
),
),
Positioned(
bottom: 0,
right: 150,
child: Container(
height: 35,
width: 35,
decoration: BoxDecoration(
border: Border.all(width: 2, color: Colors.blue),
shape: BoxShape.circle,
color: Colors.white,
),
child: IconButton(icon: Icon(Icons.edit), color: Colors.blue,iconSize:
17, onPressed: () async {
getImage(context);
},),
),
)
],
),
SizedBox(height: 40),
TextFormField(
initialValue: userData.Username,
onChanged: (val) => setState(() => _UserName = val),
validator: (input){
if (input.isEmpty) {
return 'Please enter a username';
}
if(input.length < 6){
return 'Your username needs to be at least 6 characters';
}else if(input.length > 12){
return 'Your username needs to be at most 12 characters';
}
if (!RegExp(
r'^[a-zA-Z0-9]+$')
.hasMatch(input)) {
return 'a-z, A-Z, 0-9';
}
},
focusNode: myFocusNode1,
style: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
fontFamily: 'Orbitron',
),
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.circular(25.0),
),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white, width: 1.0),
borderRadius: BorderRadius.circular(25.0),
),
icon: Icon(Icons.edit, color: Colors.blue,),
contentPadding: EdgeInsets.only(bottom: 3),
labelText: "Username",
labelStyle: TextStyle(color: myFocusNode1.hasFocus ? Colors.blue : Colors.white),
floatingLabelBehavior: FloatingLabelBehavior.always,
prefixIcon: myFocusNode1.hasFocus ? Icon(Icons.account_circle, color: Colors.blue,): Icon(Icons.account_circle, color: Colors.white,),
hintStyle: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
fontFamily: 'Orbitron',
),
),
),
SizedBox(height: 35),
Row(
children: [
SizedBox(width: 40,),
RaisedButton(
onPressed: (){
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context) => HomeScreen()));
},
color: Colors.white,
padding: EdgeInsets.symmetric(horizontal: 10),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
elevation: 2,
child: Text("CANCEL",
style:TextStyle(
color: Colors.black,
fontSize: 25,
fontWeight: FontWeight.bold,
fontFamily: 'Orbitron',
letterSpacing: 2.2,
),),
),
SizedBox(width: 30,),
RaisedButton(
onPressed: () async{
if(_formkey.currentState.validate()){
await DatabaseService(uid: user.uid).updateUserData(
_UserName ?? userData.Username,
_Email ?? userData.Email,
_URL ?? userData.URL);
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (context) => LoadingUpdate()));
}
},
color: Colors.blue,
padding: EdgeInsets.symmetric(horizontal: 30),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
elevation: 2,
child: Text("SAVE" ,style:TextStyle(
color: Colors.black,
fontSize: 27,
fontWeight: FontWeight.bold,
fontFamily: 'Orbitron',
letterSpacing: 2.2,
),),
)
],
),
],
)
),
),
);
}else{
return Center(
child: SpinKitFadingCircle(color: Colors.white, size: 20.0),
heightFactor: 29,
);
}
}
);
}
}
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
color: Colors.blue, // <--- border color
width: 5.0,
),
);
dnkjcnsjkndkcnsjkcnkjsndckjnsdkjcnsjkdcnkjnsdkcjnsd
skcnkjsndcknsdkjcnkjsdcnkjnsdjkcnsjkdcnjknsdc
scdhbsdjbcjhsdbcjhbsdhjcbsjhdcbhjdbsjdbcjhsbdc
scjbsdjhcsjdcbjhsdbcjhbsdc

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
try {
DocumentSnapshot document = await _firestore
.collection('SerX')
.doc(documentID) //replace with the document id
.get();
Map<String, dynamic> json = document.data() // your data
// for example to get the email value -> json["Email"]
} catch (e) {
throw Exception();
}

Related

Late initialising error in flutter while working with firebase

I'm working on this app to help people find the fitting wine for their meal. Now I wanted the user to be able to select the specific meal he or she is currently enjoying to have a better prediction what wine fits best. Now I tried implementing that but I'm getting this late error field must be initialised... I think I know where its coming from but I dont know how to solve it this is the code of the screen:
class _AskSomellierStep4ScreenState extends State<AskSomellierStep4Screen> {
late QueryDocumentSnapshot<Map<String, dynamic>> _selectedSnapshot;
List<String> dataLabel = [
'Home',
'Search',
'Account',
];
late Future resultsLoaded;
getResults() async {
var data = await FirebaseFirestore.instance
.collection(widget.wineOrMeal)
.where('type', isEqualTo: widget.selectedCuisine)
.get();
setState(() {
allResults = data.docs;
});
filterResultsList();
return data.docs;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...
Padding(
padding: const EdgeInsets.only(
left: 35,
top: 5,
),
child: SizedBox(
height: 370,
width: 320,
child: Center(
child: ListView.builder(
dragStartBehavior: DragStartBehavior.down,
scrollDirection: Axis.vertical,
itemCount: filteredResults.length,
itemBuilder: (context, index) => widget.mealVSWine
? PrefInformationCardWine(
snapShotDocument: filteredResults[index],
cardColor: Theme.of(context).primaryColor,
isSelected:
filteredResults[index] == _selectedSnapshot,
onSelected: () {
setState(() {
_selectedSnapshot = filteredResults[index];
});
},
)
: PrefInformationCardMeal(
snapShotDocument: filteredResults[index],
cardColor: Theme.of(context).primaryColor,
isSelected:
filteredResults[index] == _selectedSnapshot,
onSelected: () {
setState(() {
_selectedSnapshot = filteredResults[index];
});
},
),
),
),
)),
Padding(
padding: const EdgeInsets.only(
left: 35,
top: 25,
),
child: SubmitSettingChangesButton(
buttonText: 'Continue',
cancelText: 'Cancel',
cancelOnTap: () {
Navigator.pop(context);
},
continueOnTap: () {
Navigator.pushAndRemoveUntil(
context,
createRoute(FindingRecommendationScreen(
snapshotName: _selectedSnapshot,
)),
(route) => false);
},
),
),
...
If you need any further information just give me a note. I would be very thankful if you could help me with this:)
Code Screen 4:
class AskSomellierStep4Screen extends StatefulWidget {
const AskSomellierStep4Screen({
Key? key,
required this.stepDescription,
required this.wineOrMeal,
required this.mealVSWine,
required this.selectedCuisine,
}) : super(key: key);
final String wineOrMeal;
final String stepDescription;
final bool mealVSWine;
final String selectedCuisine;
#override
State<AskSomellierStep4Screen> createState() =>
_AskSomellierStep4ScreenState();
}
class _AskSomellierStep4ScreenState extends State<AskSomellierStep4Screen> {
QueryDocumentSnapshot<Map<String, dynamic>>? _selectedSnapshot;
List<String> dataLabel = [
'Home',
'Search',
'Account',
];
late Future resultsLoaded;
List<IconData> data = [
CustomIcons.home,
CustomIcons.search,
CustomIcons.user,
];
getResults() async {
var data = await FirebaseFirestore.instance
.collection(widget.wineOrMeal)
.where('type', isEqualTo: widget.selectedCuisine)
.get();
setState(() {
allResults = data.docs;
});
filterResultsList();
return data.docs;
}
List allResults = [];
List filteredResults = [];
onSearchChanged() {
print(searchController.text);
filterResultsList();
}
filterResultsList() {
var showResults = [];
if (searchController.text != '') {
// we have a search parameter
for (var searchSnapshot in allResults) {
var name = searchSnapshot['name'].toLowerCase();
if (name.contains(searchController.text.toLowerCase())) {
showResults.add(searchSnapshot);
}
}
} else {
// we do not have a search parameter
showResults = List.from(allResults);
}
setState(() {
filteredResults = showResults;
});
}
TextEditingController searchController = TextEditingController();
#override
void initState() {
super.initState();
searchController.addListener(onSearchChanged);
}
#override
void dispose() {
searchController.removeListener(onSearchChanged);
searchController.dispose();
super.dispose();
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
resultsLoaded = getResults();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HomeScreenHeader(
subText: 'Wine and Food',
mainText: 'Ask your Somellier',
boxWidth: 238,
),
Padding(
padding: const EdgeInsets.only(
left: 172,
top: 92,
),
child: Text(
'Step 4',
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).indicatorColor,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 97,
),
child: Text(
widget.stepDescription,
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).primaryColorLight,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 35,
top: 25,
),
child: Stack(
children: [
Container(
height: 35,
width: 320,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(20.0),
),
),
Positioned(
left: 10,
top: 14.5,
child: SizedBox(
height: 21,
width: 300,
child: TextField(
controller: searchController,
style: GoogleFonts.poppins(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold)),
decoration: InputDecoration(
hintText: 'Search',
hintStyle: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).hintColor,
fontSize: 16,
fontWeight: FontWeight.bold),
),
border: InputBorder.none,
),
),
),
),
Positioned(
left: 320 - 35,
top: 119 - 110,
child: SizedBox(
height: 17,
width: 17,
child: SvgPicture.asset(
'assets/icons/general/search.svg',
color: Theme.of(context).indicatorColor,
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(
left: 35,
top: 15,
),
child: Text(
'Popular Choices',
style: GoogleFonts.poppins(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 35,
top: 5,
),
child: SizedBox(
height: 370,
width: 320,
child: Center(
child: ListView.builder(
dragStartBehavior: DragStartBehavior.down,
scrollDirection: Axis.vertical,
itemCount: filteredResults.length,
itemBuilder: (context, index) => widget.mealVSWine
? PrefInformationCardWine(
snapShotDocument: filteredResults[index],
cardColor: Theme.of(context).primaryColor,
isSelected:
filteredResults[index] == _selectedSnapshot,
onSelected: () {
setState(() {
_selectedSnapshot = filteredResults[index];
});
},
)
: PrefInformationCardMeal(
snapShotDocument: filteredResults[index],
cardColor: Theme.of(context).primaryColor,
isSelected:
filteredResults[index] == _selectedSnapshot,
onSelected: () {
setState(() {
_selectedSnapshot = filteredResults[index];
});
},
),
),
),
)),
Padding(
padding: const Ed
geInsets.only(
left: 35,
top: 25,
),
child: SubmitSettingChangesButton(
buttonText: 'Continue',
cancelText: 'Cancel',
cancelOnTap: () {
Navigator.pop(context);
},
continueOnTap: () {
_selectedSnapshot != null
? () {
Navigator.pushAndRemoveUntil(
context,
createRoute(FindingRecommendationScreen(
snapshotName: _selectedSnapshot,
)),
(route) => false);
}
: null;
},
),
),
Padding(
padding: const EdgeInsets.only(
top: 15,
left: 171,
),
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: SizedBox(
height: 16,
width: 47,
child: Center(
child: Text(
'Go Back',
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).indicatorColor,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
),
],
),
);
}
}
Code Screen 5:
class FindingRecommendationScreen extends StatefulWidget {
const FindingRecommendationScreen({
Key? key,
required this.snapshotName,
}) : super(key: key);
final QueryDocumentSnapshot<Map<String, dynamic>>? snapshotName;
#override
State<FindingRecommendationScreen> createState() =>
_FindingRecommendationScreenState();
}
class _FindingRecommendationScreenState
extends State<FindingRecommendationScreen> {
bool progressDone = true;
late Future<IconData> iconSnapshot;
Future<bool> animationDone() async {
await Future.delayed(const Duration(milliseconds: 3000), () {
setState(() {
progressDone = true;
});
});
return progressDone;
}
Future<IconData> iconData(Future<bool> progress) async {
if (await progress == true) {
return Icons.home;
}
print('function used');
return Icons.done;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 35,
vertical: 100,
),
child: Text(
'Your Somellier is searching...',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).indicatorColor,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
Padding(
padding: EdgeInsets.only(
left: (MediaQuery.of(context).size.width - 200) / 2,
right: (MediaQuery.of(context).size.width - 200) / 2,
top: 50,
),
child: CircularPercentIndicator(
radius: 120,
lineWidth: 4.0,
circularStrokeCap: CircularStrokeCap.round,
animation: true,
animationDuration: 3000,
percent: 1,
// center: FutureBuilder<IconData>(
// future: iconData(animationDone()),
// builder: (context, snapshot) {
// return Icon(
// snapshot.data,
// color: Colors.white,
// );
// },
// ),
// center: const Icon(
// Icons.done_rounded,
// color: Colors.white,
// size: 90,
// ),
center: Text(
'Finding Wine 🍷',
style: GoogleFonts.poppins(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
progressColor: Theme.of(context).indicatorColor,
),
),
Padding(
padding: const EdgeInsets.only(
left: 35,
right: 35,
top: 200,
),
child: GestureDetector(
onTap: () {
Navigator.pushAndRemoveUntil(
context,
createRoute(const SomellierResultScreen()),
(route) => false);
},
child: Container(
height: 50,
width: MediaQuery.of(context).size.width - 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
25,
),
color: Theme.of(context).primaryColor,
),
child: Center(
child: Text(
widget.snapshotName?['name'],
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: Theme.of(context).indicatorColor,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
),
],
),
);
}
}
Problem
The problem with _selectedSnapshot is that you use it before you ever initialize it with a value.
In your code, you are using
isSelected: filteredResults[index] == _selectedSnapshot,
This causes the error because _selectedSnapshot has no value assigned yet. In your code you assign your value only, when the user taps one of the cards.
onSelected: () {
setState(() {
_selectedSnapshot = filteredResults[index];
});
},
But you never get there, since the screen can't be build because of the error thrown.
Solution
Instead of
late QueryDocumentSnapshot<Map<String, dynamic>> _selectedSnapshot;
use
QueryDocumentSnapshot<Map<String, dynamic>>? _selectedSnapshot = null;
With the ?-Operator you allow your variable _selectedSnapshot to be null.
This means in your context, the user has not yet chosen one option.
You may want to disable the continue button until the user has chosen an option:
continueOnTap: _selectedSnapshot != null ? () {
Navigator.pushAndRemoveUntil(context, createRoute(FindingRecommendationScreen( snapshotName: _selectedSnapshot, )), (route) => false);
} : null,
This checks if _selectedSnapshot is not null. If so the user can continue. Otherwise the Button-Callback is null, which means nothing will happen, if the user presses continue.

Null check operator used on a null value while querying the User-Data

So I am creating a chat-app. I need to show the list of all users in the firebase by mentioning their user-name and email.
I am getting the above stated error on line 56.
Also if I remove the null check operator in the line
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
And replace late at the beginning it will produce late initialization error.
import 'package:chatapp/services/database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Search extends StatefulWidget {
_Search createState() => _Search();
}
class _Search extends State<Search> {
QuerySnapshot <Map<String, dynamic>>? searchResultSnapshot;
bool isLoading = false;
bool haveUserSearched = false;
DatabaseMethods databaseMethods = new DatabaseMethods();
var searchEditingController = TextEditingController();
InitiateSearch() async {
if (searchEditingController.text.isNotEmpty) {
setState(() {
isLoading = true;
});
await databaseMethods.GetUserByUsername(searchEditingController.text)
.then((snapshot) {
searchResultSnapshot = snapshot;
print("$searchResultSnapshot");
setState(() {
isLoading = false;
haveUserSearched = true;
});
});
}
}
Widget UserList() {
return Container(
height: 500,
child: ListView.builder(
itemCount: searchResultSnapshot?.docs.length,
itemBuilder: (context, index) {
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
}),
);
}
Widget UserTile(String? userName, String? userEmail) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
),
Spacer(),
GestureDetector(
onTap: () {
null;
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(24)),
child: Text(
"Message",
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onPressed: () {
Navigator.pop(context);
});
},
),
title: Text('Search'),
),
body: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
Container(
height: 36,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10)),
boxShadow: [
BoxShadow(
color: Colors.black,
),
BoxShadow(
color: Colors.black,
spreadRadius: -12.0,
blurRadius: 12.0,
),
],
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 0, horizontal: 10.0),
child: TextFormField(
style: TextStyle(color: Colors.black),
controller: searchEditingController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search',
hintStyle: TextStyle(color: Colors.grey),
icon: GestureDetector(
onTap: () {
InitiateSearch();
},
child: Icon(
Icons.search,
color: Colors.grey,
),
),
suffixIcon: IconButton(
onPressed: searchEditingController.clear,
icon: Icon(
Icons.cancel_rounded,
color: Colors.grey,
),
),
),
),
),
), //Search
SizedBox(
height: 12,
),
UserList(),
],
),
));
}
}
Here is my Database file.
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseMethods {
GetUserByUsername(String username) async {
return await
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["userName"]);
});
});
}
Future<void> UploadUserInfo(userData) async {
FirebaseFirestore.instance.collection("users").add(userData).catchError((e) {
print(e.toString());
});
}
}
I would really appritiate your help on this.
You can replace below piece of code
children: [
Text(
userName!, //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail!,
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
with
children: [
Text(
userName ?? "", //error here
style: TextStyle(color: Colors.white, fontSize: 16),
),
Text(
userEmail ?? "",
style: TextStyle(color: Colors.white, fontSize: 16),
)
],
In place of
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"],
searchResultSnapshot?.docs[index].data()["userEmail"],
);
use this
return UserTile(
searchResultSnapshot?.docs[index].data()["userName"]??"",
searchResultSnapshot?.docs[index].data()["userEmail"]??"",
);
And replace the String? with String in (Remove ?)
Widget UserTile(String userName, String userEmail)
and use the value like the following
Text(userName,style: TextStyle(color: Colors.white, fontSize: 16),),

How to compare two values from two different collections from firebase?

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.

firebase is not connection with flutter app

what is the problem ?
the loading widget is working after that not Connection widget is running
how I can solve this problem
my code:
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:marwa_app/component/myResponsiveLibrary.dart'; import 'package:marwa_app/component/Logo.dart'; import 'package:marwa_app/component/MyDrawer.dart'; import 'package:geolocator/geolocator.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart';
class Reporting extends StatefulWidget { #override
_ReportingState createState() => _ReportingState(); }
class _ReportingState extends State<Reporting> { final formKey = GlobalKey<FormState>(); final scaffoldKey = GlobalKey<ScaffoldState>();
BoxDecoration boxDecoration() {
return BoxDecoration(
color: MainModel().mainColor,
borderRadius: BorderRadius.all(Radius.circular(40.0)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
spreadRadius: 5,
blurRadius: 5,
offset: Offset(2, 2), // changes position of shadow
),
],
); }
TextStyle titleStyle() {
return TextStyle(
color: MainModel().whiteColor,
fontSize: MainModel().setFont(MainModel().largeFont, getWidth())); }
TextStyle textStyle() {
return TextStyle(
color: MainModel().whiteColor,
fontSize: MainModel().setFont(MainModel().middleFont, getWidth()),
); }
double getWidth() {
return MediaQuery.of(context).size.width; }
final _name = TextEditingController(); final _phone = TextEditingController(); final _emType = TextEditingController(); double lat; double lon; bool _initialized = false; bool _error
= false;
void initializeFlutterFire() async {
try {
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch(e) {
// Set `_error` state to true if Firebase initialization fails
setState(() {
_error = true;
});
} }
#override void initState() {
initializeFlutterFire();
super.initState(); } #override Widget build(BuildContext context) {
if(_error) {
return notConnection();
}
if (!_initialized) {
return Loading();
}
return isConnection(); }
Widget isConnection() {
final widthScreen = MediaQuery.of(context).size.width;
return Scaffold(
key: scaffoldKey,
backgroundColor: MainModel().mainColor,
appBar: AppBar(
backgroundColor: Color(0xff323266),
leading: IconButton(
icon: Icon(
Icons.notifications_active,
color: MainModel().thirdColor,
),
onPressed: () => {}),
title: Logo(),
centerTitle: true,
actions: [
Builder(
builder: (context) => IconButton(
icon: Icon(
Icons.menu,
color: MainModel().thirdColor,
),
onPressed: () => Scaffold.of(context).openEndDrawer(),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
endDrawer: Drawer(
child: MyDrawer(),
),
body: ListView(
padding: EdgeInsets.only(
top: MainModel()
.setPadding(MainModel().largePadding, widthScreen)),
children: [
Form(
key: formKey,
child: Column(
children: [
Directionality(
textDirection: TextDirection.rtl,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
margin: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.centerRight,
decoration: boxDecoration(),
child: TextFormField(
controller: _name,
textDirection: TextDirection.rtl,
autofocus: true,
decoration: InputDecoration(
border: InputBorder.none,
hintStyle: textStyle(),
hintText: 'الاسم الرباعي'),
validator: (value) {
if (value.isEmpty) {
return "يرجى ادخل الاسم";
} else {
return null;
}
},
),
),
),
Padding(
padding: EdgeInsets.only(
top: MainModel().setPadding(
MainModel().middlePadding, widthScreen)),
),
Directionality(
textDirection: TextDirection.rtl,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
margin: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.centerRight,
decoration: boxDecoration(),
child: TextFormField(
controller: _phone,
keyboardType: TextInputType.number,
textDirection: TextDirection.rtl,
autofocus: true,
decoration: InputDecoration(
border: InputBorder.none,
hintStyle: textStyle(),
hintText: 'رقم الهاتف'),
validator: (value) {
if (value.isEmpty) {
return "يرجى ادخال رقم الهاتف";
} else {
return null;
}
},
),
),
),
Padding(
padding: EdgeInsets.only(
top: MainModel().setPadding(
MainModel().middlePadding, widthScreen)),
),
Directionality(
textDirection: TextDirection.rtl,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
margin: EdgeInsets.symmetric(horizontal: 20),
alignment: Alignment.centerRight,
decoration: boxDecoration(),
child: TextFormField(
controller: _emType,
textDirection: TextDirection.rtl,
autofocus: true,
decoration: InputDecoration(
border: InputBorder.none,
hintStyle: textStyle(),
hintText: 'نوع الابلاغ'),
validator: (value) {
if (value.isEmpty) {
return "يرجى ادخال نوع الابلاغ (الحالة)";
} else {
return null;
}
},
),
),
),
Padding(
padding: EdgeInsets.only(
top: MainModel().setPadding(
MainModel().middlePadding, widthScreen)),
),
Container(
child: GestureDetector(
onTap: () async {
bool isLocationServiceEnabled =
await Geolocator.isLocationServiceEnabled();
if (isLocationServiceEnabled == true) {
Position position =
await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
lon = position.longitude;
lat = position.latitude;
} else {
print(
'امنح التطبيق من الوصول الى موقع... ثم اعد الارسال');
}
},
child: Image.asset('images/location.png')),
),
Padding(
padding: EdgeInsets.only(
bottom: MainModel().setPadding(
MainModel().largePadding * 2, widthScreen))),
RaisedButton(
onPressed: () {
Firebase.initializeApp();
if (formKey.currentState.validate()) {
// save data in firebase
FirebaseFirestore.instance
.collection('Data')
.doc()
.set({
'name': _name,
'phone': _phone,
'em-type': _emType,
});
scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text('تم ارسال بياناتك .... '
'سيتم التواصل معك من الجهات المختصة')));
}
},
child: Text('ارسال'),
)
],
))
],
)); }
Widget notConnection() {
final widthScreen = MediaQuery.of(context).size.width;
return Scaffold(
key: scaffoldKey,
backgroundColor: MainModel().mainColor,
appBar: AppBar(
backgroundColor: Color(0xff323266),
leading: IconButton(
icon: Icon(
Icons.notifications_active,
color: MainModel().thirdColor,
),
onPressed: () => {}),
title: Logo(),
centerTitle: true,
actions: [
Builder(
builder: (context) => IconButton(
icon: Icon(
Icons.menu,
color: MainModel().thirdColor,
),
onPressed: () => Scaffold.of(context).openEndDrawer(),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
endDrawer: Drawer(
child: MyDrawer(),
),
body: ListView(
padding: EdgeInsets.only(
top: MainModel()
.setPadding(MainModel().largePadding, widthScreen)),
children: [
Container(
child: Center(
child: Text('not Connection of Database'),
),
)
])); }
Widget Loading() {
final widthScreen = MediaQuery.of(context).size.width;
return Scaffold(
key: scaffoldKey,
backgroundColor: MainModel().mainColor,
appBar: AppBar(
backgroundColor: Color(0xff323266),
leading: IconButton(
icon: Icon(
Icons.notifications_active,
color: MainModel().thirdColor,
),
onPressed: () => {}),
title: Logo(),
centerTitle: true,
actions: [
Builder(
builder: (context) => IconButton(
icon: Icon(
Icons.menu,
color: MainModel().thirdColor,
),
onPressed: () => Scaffold.of(context).openEndDrawer(),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
endDrawer: Drawer(
child: MyDrawer(),
),
body: Container(
child: Center(
child: Text('Loading'),
),
)
); } }
I don't have any error on compiler but not connected firebase.
just I want to take data from textfeild and saved in firebase.
my data is (name, phone, location, type of emergency).

While creating new account screen keeps spinning in flutter

I'm new to flutter and I have created an application with login/signup screens and connected my app to fire base, it's successfully connected but when signup or login it keeps spinning. However, I can see in firebase user is added but it doesn't get access to application home screen.
Here is my dart code for sign up:
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_login_screen/model/User.dart';
import 'package:flutter_login_screen/ui/home/HomeScreen.dart';
import 'package:flutter_login_screen/ui/services/Authenticate.dart';
import 'package:flutter_login_screen/ui/utils/helper.dart';
import 'package:image_picker/image_picker.dart';
import '../../constants.dart' as Constants;
import '../../constants.dart';
import '../../main.dart';
File _image;
class SignUpScreen extends StatefulWidget {
#override
State createState() => _SignUpState();
}
class _SignUpState extends State<SignUpScreen> {
TextEditingController _passwordController = new TextEditingController();
GlobalKey<FormState> _key = new GlobalKey();
bool _validate = false;
String firstName, lastName, email, mobile, password, confirmPassword;
#override
Widget build(BuildContext context) {
if (Platform.isAndroid) {
retrieveLostData();
}
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.transparent,
iconTheme: IconThemeData(color: Colors.black),
),
body: SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.only(left: 16.0, right: 16, bottom: 16),
child: new Form(
key: _key,
autovalidate: _validate,
child: formUI(),
),
),
),
);
}
Future<void> retrieveLostData() async {
final LostDataResponse response = await ImagePicker.retrieveLostData();
if (response == null) {
return;
}
if (response.file != null) {
setState(() {
_image = response.file;
});
}
}
_onCameraClick() {
final action = CupertinoActionSheet(
message: Text(
"Add profile picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Choose from gallery"),
isDefaultAction: false,
onPressed: () async {
Navigator.pop(context);
var image =
await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
isDestructiveAction: false,
onPressed: () async {
Navigator.pop(context);
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
Widget formUI() {
return new Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: Text(
'Create new account',
style: TextStyle(
color: Colors.deepOrange[900],
fontWeight: FontWeight.bold,
fontSize: 25.0),
)),
Padding(
padding:
const EdgeInsets.only(left: 8.0, top: 32, right: 8, bottom: 8),
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
CircleAvatar(
radius: 65,
backgroundColor: Colors.grey.shade400,
child: ClipOval(
child: SizedBox(
width: 170,
height: 170,
child: _image == null
? Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
)
: Image.file(
_image,
fit: BoxFit.cover,
),
),
),
),
Positioned(
left: 80,
right: 0,
child: FloatingActionButton(
backgroundColor: Color(COLOR_ACCENT),
child: Icon(Icons.camera_alt),
mini: true,
onPressed: _onCameraClick),
)
],
),
),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
validator: validateName,
onSaved: (String val) {
firstName = val;
},
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'First Name',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
validator: validateName,
onSaved: (String val) {
lastName = val;
},
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Last Name',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
validator: validateMobile,
onSaved: (String val) {
mobile = val;
},
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Mobile Number',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding:
const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
validator: validateEmail,
onSaved: (String val) {
email = val;
},
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(
vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Email Address',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))))),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
obscureText: true,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
controller: _passwordController,
validator: validatePassword,
onSaved: (String val) {
password = val;
},
style: TextStyle(height: 0.8, fontSize: 18.0),
cursorColor: Colors.deepOrange[900],
decoration: InputDecoration(
contentPadding:
new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Password',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900],
width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))),
)),
ConstrainedBox(
constraints: BoxConstraints(minWidth: double.infinity),
child: Padding(
padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
child: TextFormField(
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) {
_sendToServer();
},
obscureText: true,
validator: (val) =>
validateConfirmPassword(_passwordController.text, val),
onSaved: (String val) {
confirmPassword = val;
},
style: TextStyle(height: 0.8, fontSize: 18.0),
cursorColor: Colors.deepOrange[900],
decoration: InputDecoration(
contentPadding:
new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
fillColor: Colors.white,
hintText: 'Confirm Password',
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.deepOrange[900], width: 2.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
))),
),
),
Padding(
padding: const EdgeInsets.only(right: 40.0, left: 40.0, top: 40.0),
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: RaisedButton(
color: Color(Constants.FACEBOOK_BUTTON_COLOR),
child: Text(
'Sign Up',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
textColor: Colors.white,
splashColor: Color(Constants.FACEBOOK_BUTTON_COLOR),
onPressed: _sendToServer,
padding: EdgeInsets.only(top: 12, bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
side: BorderSide(
color: Color(Constants.FACEBOOK_BUTTON_COLOR))),
),
),
),
],
);
}
_sendToServer() async {
if (_key.currentState.validate()) {
_key.currentState.save();
showProgress(context, 'Creating new account...', false);
var profilePicUrl = '';
try {
AuthResult result = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
if (_image != null) {
updateProgress('Uploading image...');
profilePicUrl = await FireStoreUtils()
.uploadUserImageToFireStorage(_image, result.user.uid);
}
User user = User(
email: email,
firstName: firstName,
phoneNumber: mobile,
userID: result.user.uid,
active: true,
lastName: lastName,
settings: Settings(allowPushNotifications: true),
profilePictureURL: profilePicUrl);
await FireStoreUtils.firestore
.collection(Constants.USERS)
.document(result.user.uid)
.setData(user.toJson());
hideProgress();
MyAppState.currentUser = user;
pushAndRemoveUntil(context, HomeScreen(user: user), false);
} catch (error) {
hideProgress();
(error as PlatformException).code != 'ERROR_EMAIL_ALREADY_IN_USE'
? showAlertDialog(context, 'Failed', 'Couldn\'t sign up')
: showAlertDialog(context, 'Failed',
'Email already in use. Please pick another email address');
print(error.toString());
}
} else {
print('false');
setState(() {
_validate = true;
});
}
}
#override
void dispose() {
_passwordController.dispose();
_image = null;
super.dispose();
}
}
helper:
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:progress_dialog/progress_dialog.dart';
String validateName(String value) {
String pattern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return "Name is required";
} else if (!regExp.hasMatch(value)) {
return "Name must be a-z and A-Z";
}
return null;
}
String validateMobile(String value) {
String pattern = r'(^[0-9]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0) {
return "Mobile phone number is required";
} else if (!regExp.hasMatch(value)) {
return "Mobile phone number must contain only digits";
}
return null;
}
String validatePassword(String value) {
if (value.length < 6)
return 'Password must be more than 5 charaters';
else
return null;
}
String validateEmail(String value) {
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 'Enter Valid Email';
else
return null;
}
String validateConfirmPassword(String password, String confirmPassword) {
print("$password $confirmPassword");
if (password != confirmPassword) {
return 'Password doesn\'t match';
} else if (confirmPassword.length == 0) {
return 'Confirm password is required';
} else {
return null;
}
}
//helper method to show progress
ProgressDialog progressDialog;
showProgress(BuildContext context, String message, bool isDismissible) async {
progressDialog = new ProgressDialog(context,
type: ProgressDialogType.Normal, isDismissible: isDismissible);
progressDialog.style(
message: message,
borderRadius: 10.0,
backgroundColor: Colors.deepOrange[900],
progressWidget: Container(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(
backgroundColor: Colors.white,
)),
elevation: 10.0,
insetAnimCurve: Curves.easeInOut,
messageTextStyle: TextStyle(
color: Colors.white, fontSize: 19.0, fontWeight: FontWeight.w600));
await progressDialog.show();
}
updateProgress(String message) {
progressDialog.update(message: message);
}
hideProgress() async {
await progressDialog.hide();
}
//helper method to show alert dialog
showAlertDialog(BuildContext context, String title, String content) {
// set up the AlertDialog
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.pop(context);
},
);
AlertDialog alert = AlertDialog(
title: Text(title),
content: Text(content),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
pushReplacement(BuildContext context, Widget destination) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => destination));
}
push(BuildContext context, Widget destination) {
Navigator.of(context)
.push(new MaterialPageRoute(builder: (context) => destination));
}
pushAndRemoveUntil(BuildContext context, Widget destination, bool predict) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => destination),
(Route<dynamic> route) => predict);
}
Widget displayCircleImage(String picUrl, double size, hasBorder) =>
CachedNetworkImage(
imageBuilder: (context, imageProvider) =>
_getCircularImageProvider(imageProvider, size, false),
imageUrl: picUrl,
placeholder: (context, url) =>
_getPlaceholderOrErrorImage(size, hasBorder),
errorWidget: (context, url, error) =>
_getPlaceholderOrErrorImage(size, hasBorder));
Widget _getPlaceholderOrErrorImage(double size, hasBorder) => Container(
width: size,
height: size,
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
borderRadius: new BorderRadius.all(new Radius.circular(size / 2)),
border: new Border.all(
color: Colors.white,
width: hasBorder ? 2.0 : 0.0,
),
),
child: ClipOval(
child: Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
height: size,
width: size,
)),
);
Widget _getCircularImageProvider(
ImageProvider provider, double size, bool hasBorder) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
color: const Color(0xff7c94b6),
borderRadius: new BorderRadius.all(new Radius.circular(size / 2)),
border: new Border.all(
color: Colors.white,
width: hasBorder ? 2.0 : 0.0,
),
),
child: ClipOval(
child: FadeInImage(
fit: BoxFit.cover,
placeholder: Image.asset(
'assets/images/placeholder.jpg',
fit: BoxFit.cover,
height: size,
width: size,
).image,
image: provider)),
);
}

Resources