i have problem with package health 3.4.4.
I need use this code a rebuild to other activities like BLOOD_OXYGEN or ACTIVE_ENERGY_BURNED :
This code is ok:
fetchStepBar() async {
int? steps;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
int microsecond = 0;
final midnight1 = selectedDate == null
? DateTime(now.year, now.month, now.day)
: DateTime(selectedDate!.year, selectedDate!.month, selectedDate!.day);
final stepstimefetch1 = selectedDate == null
? now
: DateTime(selectedDate!.year, selectedDate!.month, selectedDate!.day,
hour = 23, minute = 59, second = 59);
bool requested = await health.requestAuthorization([HealthDataType.STEPS]);
if (requested) {
try {
steps =
await health.getTotalStepsInInterval(midnight1, stepstimefetch1);
} catch (error) {
print("Caught exception in getTotalStepsInInterval: $error");
}
setState(() {
_nofStepsday = (steps == null) ? 0 : steps;
});
}
}
I see problem in: health.getTotalStepsInInterval
I tried rebuild code in class HealthFactory:
Future<int?> getTotalActive_energy_burnedInInterval(
DateTime startDate,
DateTime endDate,
) async {
final args = <String, dynamic>{
'startDate': startDate.millisecondsSinceEpoch,
'endDate': endDate.millisecondsSinceEpoch
};
final energy = await _channel.invokeMethod<int?>(
'getTotalActive_energy_burnedInInterval',
args,
);
return energy;
}
But!!! The problem I cannot solve is method channel -> 'getTotalActive_energy_burnedInInterval' It didn't works for me. I cannot definite this.
Can anybody help me solve this problem?
Thanks a lot
Related
I am using this code but sometimes it runs the code in wrong order. Is it possible to wait for each for loop to finish before next one starts?
void changeWeek() {
for (int i = 0; i < newactivities.length; i++) {
int year = DateTime.now().year;
DateTime startDate = DateTime(year, 1, 1);
while (startDate.weekday != DateTime.monday) {
startDate = startDate.add(const Duration(days: 1));
}
for (String weekday in newactivities[i].daylistdone) {
int offset = (int.parse(weekday)) + (int.parse(currentweek) - 1) * 7;
DateTime donedate = startDate.add(Duration(days: offset));
oldDatesDone.add(Timestamp.fromDate(donedate));
}
for (String weekday in newactivities[i].daylist) {
int offset =
(int.parse(weekday) - 1) + (int.parse(currentweek) - 1) * 7;
DateTime notdonedate = startDate.add(Duration(days: offset));
oldDatesNotDone.add(Timestamp.fromDate(notdonedate));
}
for (var i in oldDatesDone) {
oldDatesNotDone.remove(i);
}
finaloldDatesDone = newactivities[i].weekdaysdone + oldDatesDone;
finaloldDatesNotDone = newactivities[i].weekdaysnotdone + oldDatesNotDone;
act.add({
'title': newactivities[i].title,
'days': newactivities[i].daylist,
'notificationidnumber': newactivities[i].notificationidnumber,
'daysdone': myData22,
'weekdaysdone': finaloldDatesDone,
'weekdaysnotdone': finaloldDatesNotDone,
'timelist': newactivities[i].timelist,
'time': newactivities[i].time
});
FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
}
Or can I do it in another way to solve the code?
Your Firebase update returns a Future, so it is an asynchronous operation. To preserve order of calls, you need to await the result of this call:
void changeWeek() async {
// ...
await FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
Note that you need do declare the changeWeek() function as async for this to work.
I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.
I'm trying to create an app where there is a button, and when a user clicks on that button, that day's timestamp is recorded and is uploaded in firestore. And then I fetch the data from there and update a fl chart widget.
This is how I get the data from firebase, convert it to DateTime and send it to the graph building method.
Future<void> updateOfflineGraph(String uid) async {
//GraphData graphData = globalContext.watch<GraphData>();
GraphData graphData = GraphData();
List<dynamic> today = List<dynamic>();
List<DateTime> now = List<DateTime>();
try {
DocumentSnapshot _docSnapshot =
await _firestore.collection("graph").document(uid).get();
today.addAll(_docSnapshot.data()['dates']);
for (int i = 0; i < today.length; i++) {
now.add(DateTime.fromMicrosecondsSinceEpoch(
today[i].microsecondsSinceEpoch));
}
graphData.buildGraph(now);
} catch (e) {
print(e);
}
}
And this is how I process the data for the fl chart.
class GraphData with ChangeNotifier {
List<FlSpot> _data = List<FlSpot>();
List<int> _date = List<int>();
List<FlSpot> get data =>
List.unmodifiable(_data..sort((a, b) => a.x.compareTo(b.x)));
void addPoint(FlSpot spot) {
_data.add(spot);
notifyListeners();
}
void buildGraph(List<DateTime> dateTime) {
removeAllPoints();
int days = 0;
int month = dateTime[0].month;
for (int i = 0; i < dateTime.length; i++) {
if (dateTime[i].month == month) {
days++;
} else {
addMonth(days, month);
days = 0;
month = dateTime[i].month;
i--;
}
}
addMonth(days, month);
}
void addMonth(int days, int month) {
addPoint(FlSpot(month.toDouble(), days.toDouble()));
print(days);
print(month);
print(_data.length);
}
}
And then do this to update the graph.
LineChartBarData(
spots:
// [
// FlSpot(1, 3),
// FlSpot(2, 4),
// FlSpot(4, 5.5),
// FlSpot(5, 1),
// FlSpot(8, 4),
// FlSpot(12, 3),
// ],
context.watch<GraphData>().data.length > 0
? context.watch<GraphData>().data
: [FlSpot(0.0, 0.0)],
}
The problem that I'm facing is that when I do this whole thing, the points are stored in the _data list successfully, but when I try to call spots in LineChartBarData, it says that _data is null when it is called. I don't know why is this happening as the data was there in an iteration before.
I am trying to compare two DateTimes in flutter and execute a particular function using if statements. However, I have been getting NoSuchMethodError.
Here is my code:
DateTime _myNowTime; DateTime _myClickTime
_getClickTime()async{ FirebaseUser currentUser = await
FirebaseAuth.instance.currentUser();
Firestore.instance.collection('user').document(currentUser.uid).snapshots().listen((event) {
if(event.data.isNotEmpty){ setState(() { _now_time = event['now_time'];
_click_time = event['click_time']; _myNowTime = _now_time.toDate(); _myClickTime = _click_time.toDate();
});
} }); }
I want to create a function:
checkTime(){
if(_myNowTime.compareTo(_myClickTime) >= 30 minutes){
//do something ...}
}
void main() {
var now = DateTime.now();
var yesterday = now.subtract(const Duration(days: 1));
if(now == yesterday) {
print("Dates are the same");
} else print("Dates are not the same");
}
I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.