firebase is not connection with flutter app - firebase

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

Related

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.

How to update the Circular Percentage Indicator once we click each Checkbox List

I want to do the checklist section which have circular percentage indicator. The percentage should updated once the list of checklist(checkbox) is clicked. Each Checkbox should hold 25% because have 4 checklist and the overall percentage is 100. Please help me how to update the percentage.
This is the interface
class ReportForm extends StatefulWidget {
final int itemIndex;
final Project project;
const ReportForm({this.itemIndex, this.project});
#override
State<ReportForm> createState() => _ReportFormState();
}
class _ReportFormState extends State<ReportForm> {
FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
UserModel loggedInUser = UserModel();
double progress = 0.0;
currentProgressColor() {
if (progress >= 0.6 && progress < 0.8) {
return Colors.red;
}
if(progress >= 0.8){
return Colors.green;
}
else{
return Colors.orange;
}
}
final checklist = [
CheckBoxState(title: 'Attendance'),
CheckBoxState(title: 'Equipment Used'),
CheckBoxState(title: 'Work Performed'),
CheckBoxState(title: 'Remarks'),
];
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
height: 650,
width: 370,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(13),
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 17,
spreadRadius: -23,
color: kShadowColor,
),
],
),
child: Column(
children: <Widget>[
SizedBox(
height:40,
),
CircularPercentIndicator(
radius: 200.0,
circularStrokeCap: CircularStrokeCap.round,
lineWidth: 25.0,
progressColor: currentProgressColor(),
percent: progress,
animation: true,
animationDuration: 1500,
center: new Text("${this.progress * 100}%", style: TextStyle(
fontSize: 30,
),),
footer: new Text("Daily Report Completion",
style: TextStyle(
fontSize: 15,
color: Colors.green,
),),),
SizedBox(
height:20,
),
StreamBuilder<QuerySnapshot>(
stream: _firebaseFirestore.collection("Attendance").snapshots(),
builder: (context, snapshot) {
return GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => Attendance(
),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height:60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Attendance')),
),
),
),
);
}
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => DetailsForm(project: widget.project, itemIndex: widget.itemIndex),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Equipment Used')),
),
),
),
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => HomeScreen(),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Work Performed')),
),
),
),
),
SizedBox(
height:18,
),
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => Remarks(),
));
},
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(13.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(10.0, 2.0, 10.0, 2.0),
child: Container(
color: Colors.white,
width: 350,
height: 60,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: buildSingleCheckbox(CheckBoxState(title: 'Remarks')),
),
),
),
),
],
),
),
);
}
Widget buildSingleCheckbox(CheckBoxState checkbox) => StatefulBuilder(
builder: (context, _setState) => CheckboxListTile(
activeColor: Colors.green,
value: checkbox.value,
title: Text(checkbox.title),
onChanged: (value) =>
_setState(() => checkbox.value = value),
),
);
}
class CheckBoxState{
final String title;
bool value;
CheckBoxState({
#required this.title,
this.value = false,});
}
I did a small test you can apply according to your need
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Teste',
debugShowCheckedModeBanner: false,
home: Teste(),
);
}
}
class Teste extends StatefulWidget {
const Teste({Key? key}) : super(key: key);
#override
_TesteState createState() => _TesteState();
}
class _TesteState extends State<Teste> {
List<bool> checkboxStatus = [];
double percentage = 0.0;
final checklist = ['Attendance', 'Equipment Used', 'Work Performed', 'Remarks'];
#override
void initState() {
super.initState();
checklist.forEach((element) => checkboxStatus.add(false));
}
currentProgressColor() {
if (percentage >= 0.6 && percentage < 0.8) {
return Colors.red;
}
if (percentage >= 0.8) {
return Colors.green;
} else {
return Colors.orange;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
height: 650,
width: 370,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(13),
boxShadow: [BoxShadow(offset: Offset(0, 1), blurRadius: 17, spreadRadius: -23, color: Colors.orange)],
),
child: Column(
children: <Widget>[
SizedBox(height: 40),
CircularPercentIndicator(
animateFromLastPercent: true,
radius: 200.0,
circularStrokeCap: CircularStrokeCap.round,
lineWidth: 25.0,
progressColor: currentProgressColor(),
percent: percentage,
animation: true,
animationDuration: 1500,
center: Text('${percentage * 100} %'),
footer: Text("Daily Report Completion", style: TextStyle(fontSize: 15, color: Colors.green)),
),
SizedBox(height: 20),
Expanded(
child: ListView.builder(
itemCount: checklist.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13.0)),
elevation: 10,
child: ElevatedButton(
onPressed: () {
if (checklist[index] == 'Attendance') {
Navigator.push(context, MaterialPageRoute(builder: (context) => Attendance()));
} else if() {
/// other page
}
},
style: ElevatedButton.styleFrom(primary: Colors.white),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(checklist[index], style: TextStyle(color: Colors.black)),
Checkbox(
value: checkboxStatus[index],
onChanged: (value) {
if (checkboxStatus[index] == false) {
percentage += (1 / checklist.length);
} else {
percentage -= (1 / checklist.length);
}
setState(() => checkboxStatus[index] = !checkboxStatus[index]);
},
checkColor: Colors.white,
)
],
),
),
),
);
},
),
)
],
),
),
),
);
}
}

Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.in FLUTTER

my signup.dart file:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final _formKey = GlobalKey<FormState>();
TextEditingController _emailTextController = TextEditingController();
TextEditingController _passwordTextController = TextEditingController();
TextEditingController _nameTextController = TextEditingController();
TextEditingController _confirmPasswordTextController =
TextEditingController();
String gender;
String groupValue = "Erkek";
bool loading = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Image.asset(
'images/backg.jpg',
fit: BoxFit.fill,
width: double.infinity,
height: double.infinity,
),
Container(
color: Colors.black.withOpacity(0.4),
width: double.infinity,
height: double.infinity,
),
Padding(
padding: const EdgeInsets.only(top: 200.0),
child: Center(
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _passwordTextController,
decoration: InputDecoration(
hintText: "Ad Soyad",
icon: Icon(Icons.person),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "İsim boşluğu doldurulmalıdır.";
}
return null;
},
// ignore: missing_return
),
trailing: Icon(Icons.remove_red_eye),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: TextFormField(
controller: _emailTextController,
decoration: InputDecoration(
hintText: "Email",
icon: Icon(Icons.email),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
Pattern pattern =
r'^(([^<>()[]\.,;:\s#"]+(.[^<>()[]\.,;:\s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value))
return "Lütfen geçerli bir mail adresi giriniz.";
else
return null;
}
}),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: new Container(
color: Colors.white.withOpacity(0.4),
child: Row(
children: <Widget>[
Expanded(
child: ListTile(
title: Text(
"Erkek",
textAlign: TextAlign.end ,
style: TextStyle(color: Colors.white),
),
trailing: Radio(value: "Erkek", groupValue: groupValue, onChanged: (e)=>valueChanged(e)),
)),
Expanded(
child: ListTile(
title: Text(
"Kadın",
textAlign: TextAlign.end ,
style: TextStyle(color: Colors.white),
),
trailing: Radio(value: "Kadın", groupValue: groupValue, onChanged: (e)=>valueChanged(e)),
)),
],
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _passwordTextController,
obscureText: true,
decoration: InputDecoration(
hintText: "Şifre",
icon: Icon(Icons.lock_outline),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "Şifre boşluğu doldurulmalıdır.";
} else if (value.length < 6) {
return "Şifre 6 haneden uzun olmalı!";
}
return null;
},
// ignore: missing_return
),
trailing : IconButton(icon: Icon(Icons.remove_red_eye), onPressed: (){})
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white.withOpacity(0.4),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title : TextFormField(
controller: _confirmPasswordTextController,
obscureText: true,
decoration: InputDecoration(
hintText: "Şifreyi Doğrula",
icon: Icon(Icons.lock_outline),
border: InputBorder.none
),
// ignore: missing_return
validator: (value) {
if (value.isEmpty) {
return "Şifre boşluğu doldurulmalıdır.";
} else if (value.length < 6) {
return "Şifre 6 haneden uzun olmalı!";
}else if (_passwordTextController != value){
return "Şifreler uyuşmuyor.";
}
return null;
},
// ignore: missing_return
),
trailing : IconButton(icon: Icon(Icons.remove_red_eye), onPressed: (){}),
),
),
),
),
Padding(
padding:
const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.red.withOpacity(0.8),
elevation: 0.0,
child: MaterialButton(
onPressed: () {
validateForm();
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Kayıt Ol",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"Giriş Yap",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.red),
))),
],
)),
),
),
Visibility(
visible: loading ?? true,
child: Center(
child: Container(
alignment: Alignment.center,
color: Colors.white.withOpacity(0.9),
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
),
),
))
],
),
);
}
valueChanged(e) {
setState(() {
if (e == "Erkek") {
groupValue = e;
gender = e;
} else if (e == "Kadın") {
groupValue = e;
gender = e;
}
});
}
void validateForm() async{
FormState formState = _formKey.currentState;
if(formState.validate()){
User user = await firebaseAuth.currentUser;
if(user == null){
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
});
}
}
}
}
My Showing errors.
Performing hot reload...
Syncing files to device sdk gphone x86...
lib/pages/signup.dart:276:60: Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.
'TextEditingController' is from 'package:flutter/src/widgets/editable_text.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/editable_text.dart').
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
^
lib/pages/signup.dart:276:92: Error: The argument type 'TextEditingController' can't be assigned to the parameter type 'String'.
'TextEditingController' is from 'package:flutter/src/widgets/editable_text.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/editable_text.dart').
firebaseAuth.createUserWithEmailAndPassword(email: _emailTextController, password: _passwordTextController).then((user) => {
^
==========NEW ERRORRR=================
void validateForm() async {
FormState formState = _formKey.currentState;
if (formState.validate()) {
User user = await firebaseAuth.currentUser;
if (user == null) {
firebaseAuth
.createUserWithEmailAndPassword(
email: _emailTextController.text,
password: _passwordTextController.text)
.then((user) => {
_userServices.createUser(
{
"username": _nameTextController.text,
"email": user.email
}
)
});
}
}
}
}
Use _emailTextController.text instead of just _emailTextController.

The getter 'imgUrl' was called on null

I want to get the value of (profile.imgUrl) from Firestore but I get error:
The getter 'imgUrl' was called on null.
Receiver: null
Tried calling: imgUrl
Although the user is signed in and I can get the data in the home page but when I navigate to Account page it gives me this error.
class Account extends StatelessWidget {
final Profile profile;
Account({this.profile});
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
print(profile.imgUrl);
return StreamProvider<List<Profile>>.value(
value: DatabaseService().profiles,
child: Scaffold(
body: Stack(
children: <Widget>[
ClipPath(
child: Container(
color: Colors.green.withOpacity(0.8),
),
clipper: getClipper(),
),
Positioned(
width: 400,
top: MediaQuery.of(context).size.height / 5,
child: Column(
children: <Widget>[
Container(
width: 150.0,
height: 150.0,
decoration: BoxDecoration(
color: Colors.green,
image: DecorationImage(
image: NetworkImage(profile.imgUrl),
fit: BoxFit.cover),
borderRadius: BorderRadius.all(Radius.circular(75.0)),
boxShadow: [
BoxShadow(blurRadius: 7.0, color: Colors.black)
]),
),
SizedBox(
height: 90.0,
),
Text(
'Alex Ali',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30.0,
fontFamily: 'Montserrat',
letterSpacing: 1.5),
),
SizedBox(
height: 15.0,
),
Text(
'New Seller',
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 17.0,
color: Colors.green),
),
SizedBox(
height: 25,
),
Container(
height: 30.0,
width: 95.0,
child: Material(
borderRadius: BorderRadius.circular(20.0),
shadowColor: Colors.greenAccent,
color: Colors.green,
elevation: 7.0,
child: GestureDetector(
onTap: () {
print(profile.imgUrl);
},
child: Center(
child: Text(
'Edit Name',
style: TextStyle(color: Colors.white),
),
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: 30.0,
width: 95.0,
child: Material(
borderRadius: BorderRadius.circular(20.0),
shadowColor: Colors.redAccent,
color: Colors.red,
elevation: 7.0,
child: GestureDetector(
onTap: () async {
await _auth.signOut();
},
child: Center(
child: Text(
'Log out',
style: TextStyle(color: Colors.white),
),
),
),
),
)
],
),
)
],
)
),
);
}
}
class getClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var path = new Path();
path.lineTo(0.0, size.height / 1.9);
path.lineTo(size.width + 125, 0.0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
}
and that is Home page code:
class Home extends StatefulWidget {
#override
_Home createState() => _Home();
}
class _Home extends State<Home> {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
return StreamProvider<List<Profile>>.value(
value: DatabaseService().profiles,
child: Scaffold(
body: SafeArea(
child: ListView(
padding: EdgeInsets.symmetric(vertical: 30.0),
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 20.0, right: 120.0),
child: Text(
"What would you like to find?",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
SizedBox(height: 20.0),
SizedBox(
height: 20.0,
),
SizedBox(height: 500, child: ProfileList()),
],
),
),
),
);
}
}
Here is the code that opens Account page through BottomNavigationBar:
class Wrapper extends StatefulWidget {
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
int _currentTab = 0;
final _page = [
Home(),
Search(),
Account(),
];
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
print(user);
if (user == null) {
return Authenticate();
} else {
return Scaffold(
body: _page[_currentTab],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentTab,
onTap: (int value) {
setState(() {
_currentTab = value;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
size: 30.0,
),
title: SizedBox.shrink()),
BottomNavigationBarItem(
icon: Icon(
Icons.search,
size: 30.0,
),
title: SizedBox.shrink()),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
size: 30.0,
),
title: SizedBox.shrink(),
)
]),
);
}
}
}
You need to pass a Profile as a parameter when Account is created.
That should be done dynamically, so you can't use a fixed list.
Instead of doing this:
final _page = [
Home(),
Search(),
Account(),
];
Scaffold(
body: _page[_currentTab],
// ...
)
You should do something like this:
Widget _getPage(int pos, user User) {
switch (pos) {
case 0:
return Home();
case 1:
return Search();
case 2:
return Account(user.profile); // Assuming profile is a member of user
default:
return Container();
}
}
Scaffold(
body: _getPage(_currentTab, user),
// ...
)

Resources