Firestore flutter app gets error after 2 seconds? - firebase

I'm using the flutter_calendar_carousel package for my planner app. I'm getting the data from firestore so it shows up for like 2 seconds and then I get this error "package:flutter/src/widgets/container.dart': Failed assertion: line 316 pos 15: 'padding == null || padding.isNonNegative': is not true."
This is my code.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart' show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;
bool onDarkMode = false;
class MonthPageTest extends StatefulWidget {
#override
_MonthPageTestState createState() => _MonthPageTestState();
}
class _MonthPageTestState extends State<MonthPageTest> {
final databaseReference = Firestore.instance.collection("Planerino").document("UserSettings");
final databaseRef = Firestore.instance.collection("Eventhmonth");
darkmode() async{
try {
databaseReference.updateData({'Darkmode': onDarkMode});
}catch (e) {
print(e.toString());
}
}
#override
void initState(){
super.initState();
}
#override
void dispose(){
super.dispose();
}
toggleButton(){
setState(() {
onDarkMode = !onDarkMode;
});
darkmode();
}
//calender
DateTime _currentDate = DateTime.now();
static Widget _eventIcon = new Container(
width: 40.0,
height: 40.0,
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(1000)),
border: Border.all(color: Colors.blue, width: 6.0)),
child: new Icon(
Icons.person,
color: Colors.amber,
size: 40.0,
),
);
//function
EventList<Event> _markedDateMap = new EventList<Event>(
events: {
new DateTime(2020, 6, 24): [
new Event(
date: new DateTime(2020, 6, 13),
icon: _eventIcon,
dot: Container(
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
color: Colors.red,
),
),
],
},
);
Widget builderino(BuildContext context){
return StreamBuilder(
stream: databaseRef.snapshots(),
builder: (context, dataSnapshot){
var ref = dataSnapshot.data.documents;
for (var i = 0; i < ref.length; i++) {
String valueString = ref[i]['color'].split('(0x')[1].split(')')[0];
int value = int.parse(valueString, radix: 16);
Color newColor = new Color(value);
_markedDateMap.add(new DateTime(ref[i]['year'], ref[i]['month'], ref[i]['day']),
Event(
date: new DateTime(2020, 6, 13),
icon: _eventIcon,
dot: Container(
child: Padding(
padding: EdgeInsets.only(top: 90.0),
child: Container( alignment: Alignment.center, child: Text(ref[i]['description'], style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.w300), textAlign: TextAlign.center,)),
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
decoration: BoxDecoration(color: newColor),
),
));
}
return CalendarCarousel<Event>(
onDayPressed: (DateTime date, List<Event> events) {
this.setState(() => _currentDate = date);
events.forEach((event) => print(event.title));
},
weekendTextStyle: TextStyle(
color: Colors.red,
fontSize: 28.0,
),
markedDatesMap: _markedDateMap,
markedDateIconBuilder: (event) {
return event.dot;
},
showIconBehindDayText: true,
markedDateShowIcon: true,
markedDateIconMaxShown: 1000,
todayButtonColor: Colors.black12,
markedDateMoreShowTotal: true,
headerTextStyle: TextStyle(fontSize: 34.0, color: Colors.blue[300]),
daysTextStyle: TextStyle(fontSize: 28.0, color: onDarkMode ? Colors.white : Colors.black45),
todayTextStyle: TextStyle(fontSize: 28.0, color: onDarkMode ? Colors.white : Colors.black45),
weekdayTextStyle: TextStyle(fontSize: 28.0),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: onDarkMode ? Colors.black87 : Colors.white,
margin: EdgeInsets.symmetric(horizontal: 16.0),
child: builderino(context),
),
);
}
}
Do i need to make it async or what is the problem?

from this SO answer
TLDR
Flutter has a sophisticated but effective algorithm for rendering its widgets. Margins and Paddings are analyzed at runtime, and the final size and position of the widget is determined. When you try to issue a negative margin you are purposefully creating a not valid layout where a widget is somehow dropping out of the space it is supposed to occupy.
Consider reading the doc here.

Related

TextField input won't print to console?

I'm trying to use a custom TextField widget in my AddNoteScreen. I don't know why it's not printing the TextField input or how to get it to work. I thought having the TextEditingController was all it needed.. I'm new.. sorry to post so much code I don't know how else to explain.
Here is my custom widget:
class MyWidget extends StatefulWidget {
final Widget textFields;
MyWidget(
{required this.textFields});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController notesController = TextEditingController();
List<TextField> textFields = [];
#override
void initState() {
super.initState();
textFields.add(_buildTextField());
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
color: Colors.white,
),
height: 300,
alignment: Alignment.centerLeft,
child: ListView(
children: textFields,
),
);
}
TextField _buildTextField() {
return TextField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
prefix: Icon(
Icons.circle,
size: 10,
color: Colors.black,
),
prefixIconConstraints: BoxConstraints(
minWidth: 20,
minHeight: 10,
maxHeight: 10,
maxWidth: 20,
),
),
autofocus: true,
onSubmitted: (_) {
setState(() {
textFields.add(_buildTextField());
notesController.text + ' ';
});
}
);
}
}
My AddNoteScreen:
class AddNoteScreen extends StatefulWidget {
User user;
AddNoteScreen({
required this.user,
});
#override
State<AddNoteScreen> createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
TextEditingController notesController = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
bool loading = false;
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor:Color (0xFF162242),
elevation: 0,
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
notesController.text = '';
},
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(children: [
Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10),),
color: Colors.white,
),
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
),
SizedBox(height: 50,),
loading ? Center (child: CircularProgressIndicator(),) : Container(
height: 50,
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: ()async{
if (
notesController.text.isEmpty)
{
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All feilds are required")));
} else {
setState(() {
loading = true;
});
await FirestoreService().insertNote(notesController.text,
widget.user.uid);
CollectionReference notes = firestore.collection('notes');
QuerySnapshot allResults = await notes.get();
allResults.docs.forEach((DocumentSnapshot result) {
print(result.data());
});
setState(() {
loading = false;
});
Navigator.pop(context);
}
}, child: Text("Add Note", style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Color (0xFF162242)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
//color:Color (0xFF162242)
//ElevatedButton.styleFrom(primary: Color (0xFF162242),),
),
),
]),),
),
),
);
My FirestoreService page:
class FirestoreService{
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future insertNote(String notes, String userId)async{
try{
await firestore.collection('notes').add({
"notes":notes,
"userId":userId
});
} catch(e){
}
}
}
And my NoteModel Screen:
class NoteModelEdit {
String id;
String notes;
String userId;
NoteModelEdit({
required this.id,
required this.notes,
required this.userId
});
factory NoteModelEdit.fromJson(DocumentSnapshot snapshot){
return NoteModelEdit(
id: snapshot.id,
notes: snapshot['notes'],
userId: snapshot['userId']
);
}
}
Any help is appreciated!
I believe you are storing an empty note, which is the reason why the result from the database is empty.
This line:
if (notesController.text.isNotEmpty) // show error message
should become this:
if (notesController.text.isEmpty) // show error message
Also, this should probably change, too:
// This does nothing:
new TextEditingController().clear();
// To clear the controller:
notesController.text = '';
UPDATE
Change your code as follows to test if something
gets written into the database. Once this works, figure out how to use MyWidget correctly, as there are issues in there, too.
// OLD CODE
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
// NEW CODE
child: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
I suggest to always only change small parts of code and ensure that your code works at each small step. Do not make too many changes at once.

how to get videos from Gallery and upload it firebase firestore using Image Picker and Video Player in Flutter?

I am trying to get video from gallery and want to display them in grid view and inside container and then on save button want to upload it to firebase firestore. Firstly, I am not able get the videos from gallery and display it in UI. I have seen many examples and followed them but it is not working for me as I am new into all this and not able to put to it together, where it needs to be..Pls help me out. Thanks in advance.Though the complete code may or may not be related to my query but it may help somebody who is trying to achieve something same. This is the complete code which have play button, video length with indicator.
I think I am missing few things here:-
#override
void initState() {
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
This is where I want display the video:-
Container(
height: MediaQuery.of(context).size.height,
padding: EdgeInsets.all(20),
child:GridView.builder(
itemCount: _video.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemBuilder: (context,index){
return Container(
child: _controller.value.isInitialized ?
Stack(
children: [
VideoPlayer(_controller),
_ControlsOverlay(_controller),
],
)
:Container(),
);
}
),
),
This is where I open gallery and pick video;-
chooseVideo() async {
final pickedVideo = await picker.getVideo(
source: ImageSource.gallery,
maxDuration: const Duration(seconds: 60)
);
setState(() {
_video.add(File(pickedVideo?.path));
_controller = VideoPlayerController.file(File(_video.toString()));
});
if (pickedVideo.path == null) retrieveLostData();
}
Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
_video.add(File(response.file.path));
});
} else {
print(response.file);
}
}
This is complete code:-
class AddVideo extends StatefulWidget {
#override
_AddVideo createState() => _AddVideo();
}
class _AddVideo extends State<AddVideo> {
bool uploading = false;
double val = 0;
CollectionReference imgRef;
firebase_storage.Reference ref;
List<File> _video = [];
File videoFile;
List<String> urls = [];
final picker = ImagePicker();
final auth = FirebaseAuth.instance;
final _stoarge = FirebaseStorage.instance;
VideoPlayerController _controller;
#override
void initState() {
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
actions: [
ElevatedButton(
child: Text("SAVE", style: TextStyle(fontSize: 15)),
onPressed: () {
setState(() {
uploading = true;
});
_uploadVideo().whenComplete(() => Navigator.of(context).pop());
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.fromLTRB(25.0, 15.0, 25.0, 10.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0))),
),
],
),
body: Container(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
// padding: EdgeInsets.all(20),
child: ElevatedButton(
child: Text("Open Gallery", style: TextStyle(fontSize: 20)),
onPressed: () => !uploading ? chooseVideo() : null,
style: ElevatedButton.styleFrom(
padding: EdgeInsets.fromLTRB(25.0, 15.0, 25.0, 10.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0))),
),
),
Container(
height: MediaQuery.of(context).size.height,
padding: EdgeInsets.all(20),
child:GridView.builder(
itemCount: _video.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemBuilder: (context,index){
return Container(
child: _controller.value.isInitialized ?
Stack(
children: [
VideoPlayer(_controller),
_ControlsOverlay(_controller),
],
)
:Container(),
);
}
),
),
uploading ?
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
child: Text(
'uploading...',
style: TextStyle(fontSize: 20),
),
),
SizedBox(
height: 10,
),
CircularProgressIndicator(
value: val,
valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
)
],
)
)
: Container(),
],
),
),
),
),
);
}
chooseVideo() async {
final pickedVideo = await picker.getVideo(
source: ImageSource.gallery,
maxDuration: const Duration(seconds: 60)
);
setState(() {
_video.add(File(pickedVideo?.path));
_controller = VideoPlayerController.file(File(_video.toString()));
});
if (pickedVideo.path == null) retrieveLostData();
}
Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
_video.add(File(response.file.path));
});
} else {
print(response.file);
}
}
_uploadVideo() async {
for (var video in _video) {
var _ref = _stoarge.ref().child("videos/" + Path.basename(video.path));
await _ref.putFile(video);
String url = await _ref.getDownloadURL();
print(url);
urls.add(url);
print(url);
}
print("uploading:" + urls.asMap().toString());
await FirebaseFirestore.instance
.collection("users")
.doc(auth.currentUser.uid)
.update({"images": urls});
// .doc(auth.currentUser.uid).update({"images": FieldValue.arrayUnion(urls) });
}
}
class _ControlsOverlay extends StatelessWidget {
String getPosition() {
final duration = Duration(
milliseconds: controller.value.position.inMilliseconds.round());
return [duration.inMinutes, duration.inSeconds]
.map((seg) => seg.remainder(60).toString().padLeft(2, '0'))
.join(':');
}
const _ControlsOverlay(this.controller);
final VideoPlayerController controller;
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
AnimatedSwitcher(
duration: Duration(milliseconds: 50),
reverseDuration: Duration(milliseconds: 200),
child: controller.value.isPlaying
? SizedBox.shrink()
: Container(
color: Colors.black26,
child: Center(
child: Icon(
Icons.play_arrow,
color: Colors.white,
size: 100.0,
),
),
),
),
GestureDetector(
onTap: () {
controller.value.isPlaying ? controller.pause() : controller.play();
},
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Row(
children: [
const SizedBox(width: 8),
Expanded(child: Text(getPosition()),),
const SizedBox(width: 8),
Expanded(child: buildIndicator()),
const SizedBox(width: 8),
],
)
),
],
);
}
Widget buildIndicator() => Container(
margin: EdgeInsets.all(8).copyWith(right: 0),
height: 10,
child: VideoProgressIndicator(
controller, allowScrubbing: true,
),
);
}

Add listener with Table Calendar Flutter

Hi I'm new to Flutter (and to coding in particular) and I'm trying to make a calendar with table_calendar. I'm searching for a way to have a start and end date on my events (which are saved in Firebase). The OnDaySelected function built into the widget doesn't seem to work for this but I think the solution would be to add a listener to the _controller.selectedDay so that every time I click on a date I can call a specific function.
I've tried Value Notifier but it is called on null and I can't figure out why. I can use _controller.selectedDay to pass the date to the AddSchedule page so I'm not sure why the value on the actual calendar wouldn't be able to show up. Am I implementing ValueNotifier wrong or is there any other way to do this?
class SchedulePage extends StatefulWidget {
#override
_SchedulePageState createState() => _SchedulePageState();
}
class _SchedulePageState extends State<SchedulePage> {
CalendarController _controller;
List routes = [];
List locations = [];
List distinctLocations = [];
List filter = [];
List lastFilter = [];
List selectedEvents = [];
var daySelect;
#override
void initState() {
super.initState();
getRoutes();
_controller = CalendarController();
daySelect = ValueNotifier<DateTime>(_controller.selectedDay);
daySelect.value.notifyListeners();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
getRoutes() async {
final data = await FirebaseFirestore.instance
.collection("Routes")
.orderBy("driver")
.get();
List routeList = List();
for (int i = 0; i < data.docs.length; i++) {
routeList.add(data.docs[i]);
}
routes = routeList;
filter = routes
.where((element) => element['startDate'].toDate().isBefore(_controller.selectedDay)
&& element['endDate'].toDate().isAfter(_controller.selectedDay)).toList();
locations = filter.map((element) => element["locationName"].toString()).toList();
distinctLocations = locations.toSet().toList();
setState(() {});
}
getFilter(DateTime day) {
filter = routes
.where((element) => element['startDate'].toDate().isBefore(day)
&& element['endDate'].toDate().isAfter(day)).toList();
locations = filter.map((element) => element["locationName"].toString()).toList();
distinctLocations = locations.toSet().toList();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(...),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: 210,
decoration: BoxDecoration(color: Colors.grey[900], boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.8),
blurRadius: 10.0,
offset: Offset(0, 10),
),
]),
child: TableCalendar(
calendarController: _controller,
initialCalendarFormat: CalendarFormat.twoWeeks,
calendarStyle: CalendarStyle(
todayColor: Colors.red.withOpacity(0.7),
selectedColor: Color(0xFFF00F12),
weekendStyle: TextStyle(
color: Colors.red, fontWeight: FontWeight.w600),
markersColor: Colors.white,
markersMaxAmount: 1,
weekdayStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.w600)),
daysOfWeekStyle: DaysOfWeekStyle(
weekdayStyle: TextStyle(
color: Colors.white.withOpacity(0.5),
fontWeight: FontWeight.w600),
),
headerStyle: HeaderStyle(
formatButtonVisible: false,
centerHeaderTitle: true,
titleTextStyle: TextStyle(
color: Colors.red,
fontSize: 19.0,
),
leftChevronIcon:
Icon(Icons.chevron_left, color: Colors.white),
rightChevronIcon: Icon(
Icons.chevron_right,
color: Colors.white,
)),
),
),
SingleChildScrollView(
child: Container(
height: 800,
color: Colors.black38,
child: ValueListenableBuilder(
valueListenable: daySelect,
builder: (context, n, c){
return FutureBuilder(
future: getFilter(daySelect.value),
builder: (context, w) {
if(!w.hasData) {
return _buildSchedule();
} else {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.white,
));
}
});
},
),
),
),
],
),
),
floatingActionButton: Container(
height: 45,
width: 45,
child: FittedBox(
child: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return addSchedule(_controller.selectedDay);
}));
},
child: Text(...),
),
),
),
);
}
You can use onDaySelected with a setState to change the variable content
onDaySelected: (date, events, _){
setState(() {
_thisDay = date;
});
},

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,
});
}

How to get array data back to mobile screen from firebase (Flutter)

How to get back array data to the mobile screen.
The String in the firebase is retrieved easily but I have problem with array data.
1) main.dart :
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'firestoreservice.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'taskscreen.dart';
import 'task.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ToDo APP',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Color(0xff543B7A),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Task> items;
FirestoreService fireServ = new FirestoreService();
StreamSubscription<QuerySnapshot> todoTasks;
#override
void initState() {
super.initState();
items=new List();
todoTasks?.cancel();
todoTasks=fireServ.getTaskList().listen((QuerySnapshot snapshot){
final List<Task> tasks=snapshot.documents
.map((documentSnapshot) => Task. fromMap(documentSnapshot.data))
.toList();
setState(() {
this.items = tasks;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: <Widget>[
_myAppBar(context),
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height - 80,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Stack(children: <Widget>[
// The containers in the background
Column(children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 8.0, right: 8.0),
child: Container(
width: MediaQuery.of(context).size.width,
height: 80.0,
child: Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Material(
color: Colors.white,
elevation: 14.0,
shadowColor: Color(0x802196F3),
child: Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'${items[index].name}',
style: TextStyle(
color: Colors.black,
fontSize: 20.0),
),
Text(
'${items[index].size}',
style: TextStyle(
color: Colors.black,
fontSize: 20.0),
),
Container(
child: Image.network(
'${items[index].imageU}',
)),
],
),
),
),
),
),
),
),
]),
]);
}),
),
],
),
);
}
Widget todoType(String icontype) {
IconData iconval;
Color colorval;
switch (icontype) {
case 'travel':
iconval = FontAwesomeIcons.mapMarkerAlt;
colorval = Color(0xff4158ba);
break;
case 'shopping':
iconval = FontAwesomeIcons.shoppingCart;
colorval = Color(0xfffb537f);
break;
case 'gym':
iconval = FontAwesomeIcons.dumbbell;
colorval = Color(0xff4caf50);
break;
case 'party':
iconval = FontAwesomeIcons.glassCheers;
colorval = Color(0xff9962d0);
break;
default:
iconval = FontAwesomeIcons.tasks;
colorval = Color(0xff0dc8f5);
//
}
return CircleAvatar(
backgroundColor: colorval,
child: Icon(iconval, color: Colors.white, size: 20.0),
);
}
Widget _myAppBar(context) {
return Container(
height: 80.0,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFFFA7397),
const Color(0xFFFDDE42),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
child: Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 5,
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'ToDo Tasks',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
),
),
),
Expanded(
flex: 1,
child: Container(
child: IconButton(
icon: Icon(
FontAwesomeIcons.search,
color: Colors.white,
),
onPressed: () {
//
}),
),
),
],
)),
),
);
}
}
2) task.dart
class Task{
String _name;
String _size;
Task(this._name ,this._size);
Task.map(dynamic obj){
this._name = obj['name'];
this._size=obj['size'];
List<String> imageU= new List<String>();
}
String get name=> _name;
String get size=>_size;
Task.fromMap(Map<String,dynamic> map){
this._name = map['name'];
this._size= map['size'];
this.imageU= List.from(map['images']);
}
}
3) firestoreservice.dart
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'task.dart';
final CollectionReference myCollection =
Firestore.instance.collection('products');
class FirestoreService {
Future<Task> createTODOTask(String name, String size) async {
final TransactionHandler createTransaction = (Transaction tx) async {
final DocumentSnapshot ds = await tx.get(myCollection.document());
};
return Firestore.instance.runTransaction(createTransaction).then((mapData) {
return Task.fromMap(mapData);
}).catchError((error) {
print('error: $error');
return null;
});
}
Stream<QuerySnapshot> getTaskList({int offset, int limit}) {
Stream<QuerySnapshot> snapshots = myCollection.snapshots();
if (offset != null) {
snapshots = snapshots.skip(offset);
}
if (limit != null) {
snapshots = snapshots.take(limit);
}
return snapshots;
}
}
How to get back array data to the mobile screen. The String in the firebase is retrieved easily but I have a problem with array data.
Convert task.dart to see what solution will work:
class Task{
String name;
List<String> size= new List<String>();
Task.fromMap(Map<String,dynamic> map){
this.name = map['name'];
this.size= List.from(map['size' ]);
}
}
And make sure all the documents in the image have "size" field.

Resources