问题描述
我想从firestore中检索StepCountValue并根据realtimeAutoupdate将其显示在我的应用中。 RealtimeAutoupdate基础意味着我想要一种实时/不刷新的方法。因此,如果用户覆盖一定距离,则他/她将在应用程序中获得其全部步行步骤。
如何从数据库检索数据并将其放入容器(page.dart)
如何在自动更新上获取计步器(stepcountvalue)自动更改数据并检索 带有Firestore
如何将此数据自动更新为Firestore
这是我的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,decoration: Boxdecoration(
image: decorationImage(
image: Assetimage("assets/images/burned.png"),decoration: Boxdecoration(
image: decorationImage(
image: Assetimage("assets/images/step.png"),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",fontSize: 14.0,color: Colors.white),color: Colors.purple,new Container(
padding: EdgeInsets.only(left: 10.0),child: new Card(
child: Container(
child: Text(
"$_calories kCal",color: Colors.red,VerticalDivider(
width: 5.0,child: new Card(
child: Container(
child: Text(
"$_showcoin Coins",color: Colors.black,);
}
}
这是我的包装器。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();
}
}
}
这是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(),);
}
}
这是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();
}
}
这是brew.dart
class Brew {
final int stepCountValue;
Brew({ this.stepCountValue });
}
我希望这足以解决我的问题。我对Flutter还是很陌生,对Firebase和Firestore的了解也不多,所以这很好,如果您可以说我必须在哪里更改或添加内容。非常感谢!!!
解决方法
您可以在main.dart文件的_onData()函数中编写查询,这将在步骤中有任何更改时自动更新数据。而且,您可以轻松地使用streamBuilder实时检索数据。
例如:
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0,with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)