How can I Sign up a user on firebase? - firebase

I want to sign up a user on firebase that I store in a variable.
Here is my code :
import 'package:flutter/material.dart';
import 'package:login_signup/constants/constants.dart';
import 'package:login_signup/ui/widgets/custom_shape.dart';
import 'package:login_signup/ui/widgets/customappbar.dart';
import 'package:login_signup/ui/widgets/responsive_ui.dart';
import 'package:login_signup/ui/widgets/textformfield.dart';
import 'package:email_validator/email_validator.dart';
class SignUpScreen extends StatefulWidget {
#override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
bool checkBoxValue = false;
double _height;
double _width;
double _pixelRatio;
bool _large;
bool _medium;
TextEditingController emailEditingController = TextEditingController();
String email;
void validation() {
// email should be instantiated here
email = emailEditingController.text;
bool emailvalidated = EmailValidator.validate(email);
if (emailvalidated) {
print('Email validated');
} else{
print('email not validated');
}
}
Widget clipShape() {
return Stack(
children: <Widget>[
Opacity(
opacity: 0.75,
child: ClipPath(
clipper: CustomShapeClipper(),
child: Container(
height: _large
? _height / 8
: (_medium ? _height / 7 : _height / 6.5),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.orange[200], Colors.pinkAccent],
),
),
),
),
),
Opacity(
opacity: 0.5,
child: ClipPath(
clipper: CustomShapeClipper2(),
child: Container(
height: _large
? _height / 12
: (_medium ? _height / 11 : _height / 10),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.orange[200], Colors.pinkAccent],
),
),
),
),
),
Container(
height: _height / 5.5,
alignment: Alignment.center,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
spreadRadius: 0.0,
color: Colors.black26,
offset: Offset(1.0, 10.0),
blurRadius: 20.0),
],
color: Colors.white,
shape: BoxShape.circle,
),
child: GestureDetector(
onTap: () {
print('Adding photo');
},
child: Icon(
Icons.add_a_photo,
size: _large ? 40 : (_medium ? 33 : 31),
color: Colors.orange[200],
)),
),
],
);
}
Widget form() {
return Container(
margin: EdgeInsets.only(
left: _width / 12.0, right: _width / 12.0, top: _height / 20.0),
child: Form(
child: Column(
children: <Widget>[
firstNameTextFormField(),
SizedBox(height: _height / 60.0),
lastNameTextFormField(),
SizedBox(height: _height / 60.0),
emailTextFormField(),
SizedBox(height: _height / 60.0),
phoneTextFormField(),
SizedBox(height: _height / 60.0),
passwordTextFormField(),
],
),
),
);
}
Widget firstNameTextFormField() {
return CustomTextField(
keyboardType: TextInputType.text,
icon: Icons.person,
hint: "First Name",
);
}
Widget emailTextFormField() {
return CustomTextField(
// assign your email controller to the custom text field here,
keyboardType: TextInputType.emailAddress,
icon: Icons.email,
hint: "Email ID",
textEditingController: emailEditingController,
);
}
Widget acceptTermsTextRow() {
return Container(
margin: EdgeInsets.only(top: _height / 100.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
activeColor: Colors.orange[200],
value: checkBoxValue,
onChanged: (bool newValue) {
setState(() {
checkBoxValue = newValue;
});
}),
Text(
"I accept all terms and conditions",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: _large ? 12 : (_medium ? 11 : 10)),
),
],
),
);
}
Widget button() {
return RaisedButton(
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
onPressed: () {
validation();
},
padding: const EdgeInsets.all(12.0),
child: Text(
'SIGN UP',
style: TextStyle(fontSize: _large ? 14 : (_medium ? 12 : 10)),
),
),
);
}
I would appreciate your help.
But I need to auto login for my app too and thanks again.

I guess what you are asking is to sign in with firebase to your app using Email and Password.
In that case. The article below covers all what you want.
Sign in with email and password using firebase in flutter.
Sign in with email and password using firebase in flutter
I hope this answers your question.
UPDATED
Here is the link to the Github repository of the article above :
Github Repository

Related

Flutter Memory Leak with Firestore Futurebuilder

My app uses a Firestore database to store all of its data. I present the data in lists throughout my app by using a FutureBuilder to get the data from Firestore. The PROBLEM is that my app gets slower and slower as you use it. I checked the memory usage and it continues to grow at the same rate that the speed of the app slows down. I 'think' this is because of my usage of FutureBuilder. Does ANYONE know of a more efficient way to write this code so that it doesn't leak memory and slow down?
This is my HomePage
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TextEditingController _searchController = TextEditingController();
rive.Artboard _artboard;
RefreshController _controller;
bool _searchNotification = false;
bool _addNotification = false;
bool _personNotification = false;
bool splitErrorBool = false;
int sum;
bool phoneMode;
#override
void initState() {
_loadRiveFile();
super.initState();
}
/// Loads a Rive file
void _loadRiveFile() async {
final bytes = await rootBundle.load('assets/space_reload.riv');
final file = rive.RiveFile();
if (file.import(bytes)) {
setState(() => _artboard = file.mainArtboard
..addController(_controller = RefreshController()));
}
}
void _newNotification() {
setState(() {
_searchNotification = true;
_addNotification = true;
_personNotification = true;
});
}
#override
void dispose() {
super.dispose();
}
Widget buildRefreshWidget(
BuildContext context,
RefreshIndicatorMode refreshState,
double pulledExtent,
double refreshTriggerPullDistance,
double refreshIndicatorExtent) {
_controller.refreshState = refreshState;
_controller.pulledExtent = pulledExtent;
_controller.triggerThreshold = refreshTriggerPullDistance;
_controller.refreshIndicatorExtent = refreshIndicatorExtent;
return _artboard != null
? rive.Rive(
artboard: _artboard, fit: BoxFit.cover, alignment: Alignment.center)
: Container();
}
#override
Widget build(BuildContext context) {
double x = MediaQuery.of(context).size.width;
double y = MediaQuery.of(context).size.height;
if (x < 600) {
setState(() {
phoneMode = true;
});
} else {
setState(() {
phoneMode = false;
});
}
Location sharedData = Provider.of<Location>(context, listen: false);
List<String> searchList = _searchController.text.toUpperCase().split(' ');
List<String> endSearchList =
(_searchController.text.toUpperCase() + "\uf8ff").split(' ');
return FutureBuilder(
future: Collection<Report>(
path: '${sharedData.location}/data/reports',
searchText: searchList,
endSearchList: endSearchList)
.getName(),
builder: (BuildContext context, AsyncSnapshot snap) {
if (snap.hasData) {
List<Report> reports = snap.data;
sum = reports
.map((expense) => expense.split)
.fold(0, (prev, amount) => prev + amount);
if (sum != 100) {
splitErrorBool = true;
} else {
splitErrorBool = false;
}
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text(
sharedData.location,
style: TextStyle(
fontFamily: 'Open Sans',
fontWeight: FontWeight.bold,
fontSize: phoneMode ? 23.sp : 20),
),
centerTitle: true,
leading: Padding(
padding: const EdgeInsets.only(left: 15),
child: Image.asset(
'assets/ledger_logo.png',
),
),
actions: [
Visibility(
visible: splitErrorBool,
child: IconButton(
icon: Icon(
FontAwesome5Solid.hand_paper,
color: Colors.red,
size: phoneMode ? 30.sp : null,
),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return StopDialog();
});
}),
),
IconButton(
icon: Icon(
Icons.search,
size: phoneMode ? 30.sp : null,
),
onPressed: () {
showSearch(context: context, delegate: UserSearch());
setState(() {
_searchNotification = false;
});
}),
IconButton(
icon: Icon(
Icons.add,
size: phoneMode ? 30.sp : null,
),
onPressed: () {
Navigator.pushNamed(context, '/createUser');
setState(() {
_addNotification = false;
});
}),
Padding(
padding: EdgeInsets.only(right: phoneMode ? 10.w : 10),
child: IconButton(
icon: Icon(
Icons.person,
size: phoneMode ? 30.sp : null,
),
onPressed: () {
Navigator.pushNamed(context, '/profile');
setState(() {
_personNotification = false;
});
}),
),
],
),
body: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification is ScrollEndNotification) {
_controller.reset();
}
return true;
},
child: CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: [
CupertinoSliverRefreshControl(
refreshTriggerPullDistance: 240.0,
refreshIndicatorExtent: 240.0,
builder: buildRefreshWidget,
onRefresh: () {
return Future<void>.delayed(const Duration(seconds: 5))
..then<void>((_) {
if (mounted) {
setState(() {});
}
});
},
),
SliverSafeArea(
top: false,
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding:
EdgeInsets.only(left: phoneMode ? 5 : 10.0),
child: Column(
children: [
Container(
width: phoneMode ? 160.w : x * .385,
height: phoneMode
? MediaQuery.of(context).size.height -
75.h
: MediaQuery.of(context).size.height -
75,
child: Padding(
padding: const EdgeInsets.only(
bottom: 20, top: 20),
child: ListView(
shrinkWrap: true,
padding:
const EdgeInsets.only(bottom: 10),
primary: false,
children: reports
.map((report) =>
UsersItem(report: report))
.toList(),
),
),
),
],
),
),
Expanded(
flex: 3,
child: Padding(
padding: const EdgeInsets.only(top: 20),
child: Column(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
InkWell(
onTap: () =>
Navigator.pushReplacementNamed(
context, '/pdf'),
child: SizedBox(
width:
phoneMode ? 105.w : x * .25,
height:
phoneMode ? 110.h : x * .23,
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: phoneMode ? 4 : 5,
color: Colors.blue
.withOpacity(.5)),
borderRadius:
BorderRadius.circular(
15.0),
gradient: RadialGradient(
colors: [
const Color(0xFF5e5e5e),
const Color(0xFF424242),
],
// stops: [0.0, 0.1],
),
),
clipBehavior: Clip.antiAlias,
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding:
const EdgeInsets.all(
7.0),
child: Column(
mainAxisAlignment:
MainAxisAlignment
.spaceEvenly,
children: [
Icon(
FlutterIcons
.file_pdf_mco,
color: Colors.blue,
size: phoneMode
? 50.w
: x * .14,
),
Text(
'Pdf',
style: GoogleFonts
.poppins(
fontSize:
phoneMode
? 15
.sp
: 20,
fontWeight:
FontWeight
.w400),
),
Visibility(
visible: true,
child: Text(
'Documents',
style: TextStyle(
fontSize:
phoneMode
? 11.sp
: 15,
fontWeight:
FontWeight
.w300),
),
),
],
),
),
),
),
),
),
InkWell(
onTap: () =>
Navigator.pushReplacementNamed(
context, '/reports'),
child: SizedBox(
width:
phoneMode ? 105.w : x * .25,
height:
phoneMode ? 110.h : x * .23,
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: phoneMode ? 4 : 5,
color: Colors.green
.withOpacity(.5)),
borderRadius:
BorderRadius.circular(
15.0),
gradient: RadialGradient(
colors: [
const Color(0xFF5e5e5e),
const Color(0xFF424242),
],
// stops: [0.0, 0.1],
),
),
clipBehavior: Clip.antiAlias,
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding:
const EdgeInsets.all(
7.0),
child: Column(
mainAxisAlignment:
MainAxisAlignment
.spaceEvenly,
children: [
Icon(
FlutterIcons
.chart_bubble_mco,
color: Colors.green,
size: phoneMode
? 50.w
: x * .14,
),
Text(
'Reports',
style: GoogleFonts
.poppins(
fontSize:
phoneMode
? 15
.sp
: 20,
fontWeight:
FontWeight
.w400),
),
Visibility(
visible: true,
child: Text(
'Datasheet',
style: GoogleFonts.poppins(
fontSize:
phoneMode
? 11.sp
: 15,
fontWeight:
FontWeight
.w300),
),
),
],
),
),
),
),
),
),
],
),
SizedBox(
height: 25.h,
),
Padding(
padding: EdgeInsets.only(
left: phoneMode ? 5.w : 10,
right: phoneMode ? 5.w : 10),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
phoneMode ? 20.w : 30.0),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
const Color(0xFF424242),
const Color(0xFF424242),
],
// stops: [0.0, 0.1],
),
),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(
top: phoneMode ? 10.h : 20,
left: phoneMode ? 5.w : 5,
),
child: Row(children: [
SizedBox(
width:
phoneMode ? 5.w : 5),
Icon(
Icons.history,
color: Colors.white
.withOpacity(.8),
size: phoneMode ? 20.w : 25,
),
SizedBox(width: 5),
Text('Transaction History',
style: TextStyle(
fontSize: phoneMode
? 13.sp
: 20,
color: Colors.white
.withOpacity(
.8))),
]),
),
SizedBox(
height: phoneMode
? 510.h
: MediaQuery.of(context)
.size
.height *
.64,
child: Padding(
padding: EdgeInsets.only(
top: phoneMode
? 15.h
: 20,
left: 0,
right: 0,
bottom: phoneMode
? 10.h
: 30),
child:
SingleChildScrollView(
child: Column(
children: [
FutureBuilder(
future: Collection<
History>(
path:
'${sharedData.location}/data/history')
.getHistory(),
builder:
(BuildContext
context,
AsyncSnapshot
snap) {
if (snap
.hasData) {
List<History>
historyList =
snap.data;
return ListView(
shrinkWrap:
true,
primary:
false,
children:
historyList
.map((history) =>
HistoryItem(
history: history,
))
.toList(),
);
} else {
return Loader();
}
},
),
],
),
),
)),
],
),
),
),
],
),
),
),
],
);
}, childCount: 1),
),
),
],
),
),
);
} else {
return LoadingScreen();
}
});
}
}
That is just one page of many that uses FutureBuilder, and each time I click on a new page the memory usage gets larger. Any help is apprecieted!
Make sure to anyController.dispose() any controllers like RefreshController and TextEditingController in void dispose() {} to avoid memory leaks.
One problem with your code is that it calls setState() within the build() method. This is a problem because setState() will trigger a Widget rebuild, hence build() will be called again, which will in turn call setState() again, etc.

FormatException: Unexpected character (at character 1) error while using email_auth package

#Hello there! I am using email_auth: ^0.0.1+4 Package to confirm the user email also it worked fine for few days and I also registered 2 3 users but suddenly it has started showing this FormatException: Unexpected character (at character 1) and DOCTYPE html error. I have added signup file Please check and help. Thank you.#
SignUp Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vanfly/common.dart';
import 'package:vanfly/providers/user_provider.dart';
import 'package:vanfly/screens/home.dart';
import 'package:vanfly/widgets/loading.dart';
import 'package:email_auth/email_auth.dart';
bool verified = false;
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
TextEditingController otp = TextEditingController();
bool hidePass = true;
void sendOTP() async {
EmailAuth.sessionName = 'Vanfly';
var res = await EmailAuth.sendOtp(receiverMail: _email.value.text);
if (res) {
_key.currentState.showSnackBar(SnackBar(
content: Text("An OTP has sent to your email please verify")));
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
}
}
bool verifyOTP(){
var res = EmailAuth.validate(receiverMail: _email.value.text, userOTP: otp.value.text);
if (res) {
return verified = true;
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
return verified = false;
}
}
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating
? Loading()
: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image(
image: AssetImage(
'images/vanfly Logo/vanfly_logo.png'),
width: 300,
height: 300,
)),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _email,
decoration: InputDecoration(
hintText: "Email",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Verify')),
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(keyboardType: TextInputType.number,
controller: otp,
decoration: InputDecoration(
hintText: "otp",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Resend'),
),
icon: Icon(Icons.pin),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = !hidePass;
});
}),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.pinkAccent,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
verifyOTP();
if (verified == true &&
_formKey.currentState.validate()) {
if (!await user.signUp(_name.text,
_email.text, _password.text)) {
// ignore: deprecated_member_use
_key.currentState.showSnackBar(
SnackBar(
content:
Text("Sign up failed")));
return;
}
changeScreenReplacement(
context, MyHomePage());
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black, fontSize: 16),
))),
],
)),
),
),
],
),
);
}
}
Error
I/flutter ( 5091): Email ID is valid
I/flutter ( 5091): --This error is from the package--
I/flutter ( 5091): FormatException: Unexpected character (at character 1)
I/flutter ( 5091): <!DOCTYPE html>
I/flutter ( 5091): ^
I/flutter ( 5091): --End package error message--
The error is coming from the package itself.
The endpoint that the package calls to send the OTP is down and so it returns an error page instead of the JSON the package expected. This causes an error in parsing the HTML which is why the error says:
FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
I'll advise you to use a different service like firebase_auth for this or create an issue on the project.

flutter and firestore : change price and size dynamicly

hello iam using flutter and firebase in my project , i have a product and evert product have a price , every product have a list of sizes , i want the product to change its price when the size changes .
here is my product document :
i know that i have to change the prices into list but how to link them together in firebase or flutter .
this is my code :
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: CustomText(
text: "Select a Size",
color: Colors.white,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: DropdownButton<String>(
value: _size,
style: TextStyle(color: Colors.white),
items: widget.product.sizes
.map<DropdownMenuItem<String>>(
(value) => DropdownMenuItem(
value: value,
child: CustomText(
text: value,
color: Colors.red,
)))
.toList(),
onChanged: (value) {
setState(() {
_size = value;
});
}),
)
],
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"${widget.product.description}",
style: TextStyle(color: Colors.white)),
),
),
Padding(
padding: const EdgeInsets.all(9),
child: Material(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
appProvider.changeIsLoading();
bool success = await userProvider.addToCart(
product: widget.product,
size: _size);
if (success) {
toast("Added to Cart!");
userProvider.reloadUserModel();
appProvider.changeIsLoading();
return;
} else {
toast("Not added to Cart!");
appProvider.changeIsLoading();
return;
}
},
minWidth: MediaQuery.of(context).size.width,
child: appProvider.isLoading
? Loading()
: Text(
"Add to cart",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
SizedBox(
height: 20,
)
],
),
),
)
],
There is trigger for widget :
onChanged: (value) {
setState(() {
_size = value;
reference.setData({quantity : value}, merge: true)
});
}),
Just change the reference to document path.

Error "The method '[]' was called on null. Receiver: null Tried calling: []("0tm2JqPY0oNq5vSM74BqOufhGao1")"

I am getting this error in the poll post Page after added the voting feature to it:
The new method I added is handleTotalVotePosts to handle the count of userPostPolls(in line number 178).
I think the error is getting the userId or something which i am not Sure .
I am not sure what is actually wrong here
The method '[]' was called on null.
Receiver: null
Tried calling: []("0tm2JqPY0oNq5vSM74BqOufhGao1")
But code seems to be correct
This my **pollPost.dart**
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:justpoll/libmodels/user_model.dart';
import 'package:justpoll/screens/chat/chat_data.dart';
import 'package:justpoll/widgets/progress.dart';
import 'package:justpoll/widgets/toast_text.dart';
import '../Constants.dart';
import 'package:justpoll/widgets/custom_image.dart';
import 'package:animated_button/animated_button.dart';
class PollPost extends StatefulWidget {
final String pollPostId;
final String mediaUrl;
final String ownerId;
final String username;
final String caption;
final String category;
final String colorTheme;
final Timestamp duration;
final String question;
final dynamic votesTotal;
final String optText1;
final String optText2;
final String optText3;
final String optText4;
final String optemo1;
final String optemo2;
final String optemo3;
final String optemo4;
final String optCount1;
final String optCount2;
final String optCount3;
final String optCount4;
PollPost({
this.pollPostId,
this.mediaUrl,
this.ownerId,
this.username,
this.caption,
this.category,
this.colorTheme,
this.duration,
this.question,
this.votesTotal,
this.optText1,
this.optText2,
this.optText3,
this.optText4,
this.optemo1,
this.optemo2,
this.optemo3,
this.optemo4,
this.optCount1,
this.optCount2,
this.optCount3,
this.optCount4,
});
factory PollPost.fromDocument(DocumentSnapshot doc) {
return PollPost(
pollPostId: doc['pollPostid'],
mediaUrl: doc['mediaUrl'],
ownerId: doc['ownerId'],
username: doc['username'],
caption: doc['caption'],
category: doc['category'],
colorTheme: doc['colorTheme'],
duration: doc['Duration'],
question: doc['Question'],
votesTotal: doc['votesTotal'],
optText1: doc["options"]["1"]["optionText1"],
optText2: doc["options"]["2"]["optionText2"],
optText3: doc["options"]["3"]["optionText3"],
optText4: doc["options"]["4"]["optionText4"],
optemo1: doc["options"]["1"]["optionEmoji1"],
optemo2: doc["options"]["2"]["optionEmoji2"],
optemo3: doc["options"]["3"]["optionEmoji3"],
optemo4: doc["options"]["4"]["optionEmoji4"],
// optCount1: doc["options"]["1"]["optionCount1"],
// optCount2: doc["options"]["2"]["optionCount2"],
// optCount3: doc["options"]["3"]["optionCount3"],
// optCount4: doc["options"]["4"]["optionCount4"],
);
}
int getreactionsTotalCount(votesTotal) {
if (votesTotal == null) {
return 0;
}
int count = 0;
votesTotal.values.forEach((val) {
if (val = true) {
count += 1;
}
});
return count;
}
#override
_PollPostState createState() => _PollPostState(
pollPostId: this.pollPostId,
mediaUrl: this.mediaUrl,
ownerId: this.ownerId,
username: this.username,
caption: this.caption,
category: this.category,
colorTheme: this.colorTheme,
duration: this.duration,
question: this.question,
optText1: this.optText1,
optText2: this.optText2,
optText3: this.optText3,
optText4: this.optText4,
optemo1: this.optemo1,
optemo2: this.optemo2,
optemo3: this.optemo3,
optemo4: this.optemo4,
votesTotalCount: getreactionsTotalCount(this.votesTotal),
);
}
class _PollPostState extends State<PollPost> {
GlobalKey floatingKey = LabeledGlobalKey("Floating");
bool isFloatingOpen = false;
OverlayEntry floating;
static FirebaseAuth auth = FirebaseAuth.instance;
final userRef = FirebaseFirestore.instance.collection("users");
final pollPostsRef = FirebaseFirestore.instance.collection("pollPosts");
final String currentUserId = auth.currentUser?.uid;
final String pollPostId;
final String mediaUrl;
final String ownerId;
final String username;
final String caption;
final String category;
final String colorTheme;
final Timestamp duration;
final String question;
final String optText1;
final String optText2;
final String optText3;
final String optText4;
final String optemo1;
final String optemo2;
final String optemo3;
final String optemo4;
int votesTotalCount;
Map votesTotal;
bool isVoted;
_PollPostState({
this.pollPostId,
this.mediaUrl,
this.ownerId,
this.username,
this.caption,
this.category,
this.colorTheme,
this.duration,
this.question,
this.votesTotal,
this.votesTotalCount,
this.optText1,
this.optText2,
this.optText3,
this.optText4,
this.optemo1,
this.optemo2,
this.optemo3,
this.optemo4,
});
handleTotalVotePosts() {
bool _isVoted = votesTotal[currentUserId] == true;
if (_isVoted) {
pollPostsRef
.doc(ownerId)
.collection('usersPollPosts')
.doc(pollPostId)
.update({'votesTotal.$currentUserId': false});
setState(() {
votesTotalCount -= 1;
isVoted = false;
votesTotal[currentUserId] = false;
});
} else if (!_isVoted) {
pollPostsRef
.doc(ownerId)
.collection('usersPollPosts')
.doc(pollPostId)
.update({'votesTotal.$currentUserId': true});
setState(() {
votesTotalCount += 1;
isVoted = true;
votesTotal[currentUserId] = true;
});
}
}
OverlayEntry createFloating() {
RenderBox renderBox = floatingKey.currentContext.findRenderObject();
Offset offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(builder: (context) {
return Positioned(
left: offset.dx,
top: offset.dy - 70,
child: Material(
color: Colors.transparent,
elevation: 20,
child: ClipRRect(
borderRadius: BorderRadius.circular(40.0),
child: Container(
padding: EdgeInsets.all(5.0),
height: 50,
color: MyColors.black,
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage("You voted for $optText1 $optemo1");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child:
Text(optemo1, style: TextStyle(fontSize: 20.0)))),
Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
toastMessage("You voted for $optText2 $optemo2");
setState(() {
handleTotalVotePosts();
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child:
Text(optemo2, style: TextStyle(fontSize: 20.0)))),
optText3.isEmpty
? Text("")
: Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage(
"You voted for $optText3 $optemo3");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child: Text(optemo3,
style: TextStyle(fontSize: 20.0)))),
optText4.isEmpty
? Text("")
: Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage(
"You voted for $optText4 $optemo4");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child: Text(optemo4,
style: TextStyle(fontSize: 20.0)))),
],
),
),
),
),
);
});
}
buildPollPostHeader() {
return FutureBuilder(
future: userRef.doc(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
UserModel user = UserModel.fromMap(snapshot.data.data());
return ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
backgroundColor: Colors.grey,
),
title: GestureDetector(
onTap: () => toastMessage("showing profile"),
child: Text(
user.username,
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
subtitle: Text(category),
trailing: IconButton(
onPressed: () => toastMessage("pop up menu"),
icon: Icon(Icons.more_vert),
),
);
},
);
}
buildPollPostCenter() {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
question,
style: TextType.boldHeading,
),
),
mediaUrl == null
? Center(
child: Container(
height: 30.0,
))
: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: chachedNetworkImage(
mediaUrl,
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Column(
children: [
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
optText1,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo1),
SizedBox(
width: 25.0,
),
Text(
optText2,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo2),
],
),
],
),
SizedBox(height: 13.0),
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
optText3,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo3),
SizedBox(
width: 25.0,
),
Text(
optText4,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo4),
],
),
],
),
],
),
),
],
);
}
buildPollPostFooter() {
return Column(
children: [
Align(
alignment: Alignment.bottomLeft,
child: Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
isVoted
? GestureDetector(
key: floatingKey,
onTap: () {
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
child: Icon(
Icons.poll,
color: MyColors.offBlack,
size: 28.0,
),
)
: Icon(Icons.check_circle),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => toastMessage("show comments"),
child: Icon(
Icons.chat,
color: MyColors.offBlack,
size: 28.0,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => toastMessage("saved successfully"),
child: Icon(
Icons.bookmark,
color: MyColors.offBlack,
size: 28.0,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: () => toastMessage("sharing with friends"),
child: Align(
alignment: Alignment.topRight,
child: Icon(
Icons.send,
color: MyColors.offBlack,
size: 28.0,
),
),
),
Padding(padding: EdgeInsets.only(right: 25.0)),
],
),
),
],
),
),
),
Row(
children: [
Container(
margin: EdgeInsets.only(left: 20.0, top: 5.0),
child: Text(
"$votesTotalCount votes",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
Container(
margin: EdgeInsets.only(left: 20.0, top: 5.0),
child: Text(
"expiring in 4 days",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
)
],
),
Padding(
padding: const EdgeInsets.only(top: 5.0, bottom: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
"$username ",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: Text(caption),
),
],
),
)
],
);
}
#override
Widget build(BuildContext context) {
isVoted = (votesTotal[currentUserId] == true);
return Card(
elevation: 1.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
buildPollPostHeader(),
buildPollPostCenter(),
buildPollPostFooter(),
],
),
);
}
}
Please help me to get out of this bug.
Thank you :)
Please write the below code inside your handleTotalVotePosts method:
if(votesTotal == null){
return;
}

How to get pedometer(stepcountvalue) data on Autoupdate basis from firestore

I want to retrieve StepCountValue from firestore and display it to my app on realtimeAutoupdate basis. RealtimeAutoupdate basis means i want a realtime/without refreshing method.So, if a user cover some distance then he/she gets his/her total walking steps in app.
How to retrieve data from database and throw it in a container(page.dart)
How to get pedometer(stepcountvalue) automatic changing data on Autoupdate and retrieve
With firestore
How to update this data to firestore automatically
This is my main.dart
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_testing/models/brew.dart';
import 'package:flutter_testing/models/user.dart';
import 'package:flutter_testing/screens/Pages/page.dart';
import 'package:flutter_testing/screens/wrapper.dart';
import 'package:flutter_testing/services/auth.dart';
import 'package:flutter_testing/services/database.dart';
import 'dart:async';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:pedometer/pedometer.dart';
import 'package:provider/provider.dart';
void main() => runApp(new NewApp());
class NewApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthService().user,
child: MaterialApp(
home: Wrapper(),
),
);
}
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final AuthService _auth = AuthService();
String muestrePasos = "";
String _km = "Unknown";
String _calories = "Unknown";
String stepCountValue = 'Unknown';
String _showcoin = '0';
StreamSubscription<int> _subscription;
double _numerox; //numero pasos
double _convert;
double _kmx;
double burnedx;
double _coin;
double _porciento;
// double percent=0.1;
#override
void initState() {
super.initState();
//initPlatformState();
setUpPedometer();
}
//inicia codigo pedometer
void setUpPedometer() {
Pedometer pedometer = new Pedometer();
_subscription = pedometer.stepCountStream.listen(_onData,
onError: _onError, onDone: _onDone, cancelOnError: true);
}
void _onData(int stepCountValue1) async {
// print(stepCountValue); //impresion numero pasos por consola
setState(() {
stepCountValue = "$stepCountValue1";
// print(stepCountValue);
});
var dist = stepCountValue1; //pasamos el entero a una variable llamada dist
double y = (dist + .0); //lo convertimos a double una forma de varias
setState(() {
_numerox = y; //lo pasamos a un estado para ser capturado ya convertido a double
});
var long3 = (_numerox);
long3 = num.parse(y.toStringAsFixed(2));
var long4 = (long3 / 10000);
int decimals = 1;
int fac = pow(10, decimals);
double d = long4;
d = (d * fac).round() / fac;
print("d: $d");
getDistanceRun(_numerox);
setState(() {
_convert = d;
print(_convert);
});
}
void reset() {
setState(() {
int stepCountValue1 = 0;
stepCountValue1 = 0;
stepCountValue = "$stepCountValue1";
});
}
void _onDone() {}
void _onError(error) {
print("Flutter Pedometer Error: $error");
}
//function to determine the distance run in kilometers using number of steps
void getDistanceRun(double _numerox) {
var distance = ((_numerox * 76) / 100000);
distance = num.parse(distance.toStringAsFixed(2)); //dos decimales
var distancekmx = distance * 34;
distancekmx = num.parse(distancekmx.toStringAsFixed(2));
//print(distance.runtimeType);
var coiny = ((_numerox * 125) / 100000);
coiny = num.parse(coiny.toStringAsFixed(2));
setState(() {
_km = "$distance";
//print(_km);
});
setState(() {
_kmx = num.parse(distancekmx.toStringAsFixed(2));
});
setState(() {
_coin = num.parse(coiny.toStringAsFixed(2));
//print(_coiny);
});
}
//function to determine the calories burned in kilometers using number of steps
void getBurnedRun() {
setState(() {
var calories = _kmx; //dos decimales
_calories = "$calories";
//print(_calories);
});
}
void coins() {
setState(() {
var showcoin = _coin;
_showcoin = "$showcoin";
});
}
//fin codigo pedometer
#override
Widget build(BuildContext context) {
//print(_stepCountValue);
getBurnedRun();
coins();
return StreamProvider<QuerySnapshot>.value(
value: DatabaseService().step,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(
title: const Text('Step Counter'),
backgroundColor: Colors.black54,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('logout'),
onPressed: () async {
await _auth.signOut();
}
),
FlatButton.icon(
icon: Icon(Icons.arrow_back),
label: Text('New Page'),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => pages()));
}
),
],
),
body: new ListView(
padding: EdgeInsets.all(5.0),
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 10.0),
width: 250,
//ancho
height: 250,
//largo tambien por numero height: 300
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment
.bottomCenter, //cambia la iluminacion del degradado
end: Alignment.topCenter,
colors: [Color(0xFFA9F5F2), Color(0xFF01DFD7)],
),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(27.0),
bottomRight: Radius.circular(27.0),
topLeft: Radius.circular(27.0),
topRight: Radius.circular(27.0),
)),
child: new CircularPercentIndicator(
radius: 200.0,
lineWidth: 13.0,
animation: true,
center: Container(
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 50,
width: 50,
padding: EdgeInsets.only(left: 20.0),
child: Icon(
FontAwesomeIcons.walking,
size: 30.0,
color: Colors.white,
),
),
Container(
//color: Colors.orange,
child: Text(
'$stepCountValue',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.purpleAccent),
),
// height: 50.0,
// width: 50.0,
),
],
),
),
percent: 0.217,
//percent: _convert,
footer: new Text(
"Steps: $stepCountValue",
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12.0,
color: Colors.purple),
),
circularStrokeCap: CircularStrokeCap.round,
progressColor: Colors.purpleAccent,
),
),
Divider(
height: 5.0,
),
Container(
width: 80,
height: 100,
padding: EdgeInsets.only(left: 25.0, top: 10.0, bottom: 10.0),
color: Colors.transparent,
child: Row(
children: <Widget>[
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/distance.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
child: Text(
"$_km Km",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0),
),
),
color: Colors.white54,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/burned.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
),
color: Colors.transparent,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
child: new Card(
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/step.png"),
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
),
),
),
color: Colors.transparent,
),
),
],
),
),
Divider(
height: 2,
),
Container(
padding: EdgeInsets.only(top: 2.0),
width: 150,
//ancho
height: 30,
//largo tambien por numero height: 300
color: Colors.transparent,
child: Row(
children: <Widget>[
new Container(
padding: EdgeInsets.only(left: 40.0),
child: new Card(
child: Container(
child: Text(
"$_km Km",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.purple,
),
),
VerticalDivider(
width: 20.0,
),
new Container(
padding: EdgeInsets.only(left: 10.0),
child: new Card(
child: Container(
child: Text(
"$_calories kCal",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.red,
),
),
VerticalDivider(
width: 5.0,
),
new Container(
padding: EdgeInsets.only(left: 10.0),
child: new Card(
child: Container(
child: Text(
"$_showcoin Coins",
textAlign: TextAlign.right,
style: new TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.white),
),
),
color: Colors.black,
),
),
],
),
),
],
),
),
),
);
}
}
this is my wrapper.dart
import 'package:flutter_testing/models/user.dart';
import 'package:flutter_testing/screens/authenticate/authenticate.dart';
import 'package:flutter/material.dart';
import 'package:flutter_testing/main.dart';
import 'package:provider/provider.dart';
class Wrapper extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
// return either the Home or Authenticate widget
if (user == null){
return Authenticate();
} else {
return MyApp();
}
}
}
this is page.dart
import 'package:flutter/material.dart';
import 'package:flutter_testing/main.dart';
class pages extends StatefulWidget {
#override
_pagesState createState() => _pagesState();
}
class _pagesState extends State<pages> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.amber,
appBar: new AppBar(
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('back'), onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => MyApp())
);
}
),
],
),
body: Container(),
);
}
}
this is database.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_testing/models/brew.dart';
class DatabaseService {
final String uid;
DatabaseService({ this.uid });
// collection reference
final CollectionReference brewCollection = Firestore.instance.collection('step');
Future<void> updateUserData(int stepCountValue, int _calories, int _km , int _showcoin) async {
return await brewCollection.document(uid).setData({
'stepCountValue': stepCountValue,
'_calories': _calories,
'_km': _km,
'_showcoin': _showcoin,
});
// get brews stream
Stream<QuerySnapshot> get step {
return brewCollection.snapshots();
}
}
this is brew.dart
class Brew {
final int stepCountValue;
Brew({ this.stepCountValue });
}
I hope this is enough to solve my problem. I'm very new to Flutter and I dont know much about firebase and firestore, so it would be nice, if you can say where EXACTLY I have to change WHAT or add WHAT. Thank you so much!!!
You can write a query in the _onData() function of your main.dart file this will update the data automatically whenever there will be any change in your steps. And you can retrieve data in real time using streamBuilder easily.
for example:
void _onData(int stepCountValue1) async {
// print(stepCountValue); //impresion numero pasos por consola
setState(() {
stepCountValue = "$stepCountValue1";
});
final CollectionReference brewCollection = Firestore.instance.collection('step');
await brewCollection.document(uid).setData({
'stepCountValue': stepCountValue,
});
}

Resources