How to enable a button on given time? flutter - flutter

I am working on a project which have a complete button:
Expanded(child: ElevatedButton(
onPressed: () {
completeTrip(
list[index]['id']);
},
child: Text("Complete"),
style: ElevatedButton
.styleFrom(
primary: Colors.green,),
),
and i have a date and time in my database:
{
'from_date':'16-01-2022'
'time' :'1:15 PM'
}
what i want is to show that button only when the given is passed, before that this button must not be shown?
is there anything or any way to do it?
Thanks in advance <3.

You can use Stream.periodic
DateTime current = DateTime.now();
Stream timer = Stream.periodic( Duration(seconds: 1), (i){
current = current.add(Duration(seconds: 1));
return current;
});
timer.listen((data){
//if it reached the given time do something on your button
});
and at the end call timer.cancel;

Couldn't figure out if you wanted help in parsing your date and time or using some sort of timer for displaying the button.So I modified #Bunny1376 's answer for adding some things:
Use a boolean to check whether to show button or not:
bool showBtn = false;
In your initState or some other place, parse the date and time you received as a json as :
Map<String,String> _dateTimeJson = {
'from_date':'16-01-2022',
'time': '1:15 PM'
};
String _dateTimeString = _dateTimeJson['from_date'] + ' ' +_dateTimeJson['time'];
DateFormat _format = DateFormat('dd-mm-yyyy HH:mm a');
DateTime _dateTime = _format.parse(_dateTimeString);
Here, we have appended 'time' field with 'from_date' to form a singe dateTime String which later on is parsed as DateTime.I have used intl package for this. For more details: https://pub.dev/packages/intl
Now, add a timer that executes every second to check if current date time is more than your dateTime as:
DateTime current = DateTime.now();
Stream timer = Stream.periodic( Duration(seconds: 1), (i){
current = current.add(Duration(seconds: 1));
return current;
});
timer.listen((data){
if(current.isAfter(_dateTime)){
// show button
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
setState(() {
showBtn = true;
});
});
}
});
The logic of the button would be:
if(showBtn)...[
Expanded(child: ElevatedButton(
onPressed: () {
completeTrip(
list[index]['id']);
},
child: Text("Complete"),
style: ElevatedButton
.styleFrom(
primary: Colors.green,),
),
]

Related

How can I update the date on the bottom sheet when I have finished selecting the date picker?

I need to update the date display on bottom sheet when I select date on date picker of another bottom sheet, please help me.
date picker
need update date text
You must use StatefulWidget in bottom sheet. With this widget you can setstate in your bottom sheet.
Example usage: https://api.flutter.dev/flutter/widgets/StatefulBuilder-class.html
//used library
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
//declare variables
String hourOfPeriod = "AM";
String hour = "00";
TimeOfDay _time = TimeOfDay(hour: 00, minute: 00);
NumberFormat f = NumberFormat("00", "en_US");
//for displaying TimePicker
void _selectTime() async {
final TimeOfDay? newTime = await showTimePicker(
context: context,
initialTime: _time,
helpText: "RESCHEDULE TIME",
);
if (newTime != null) {
setState(() {
_time = newTime;
hourOfPeriod = _time.period == DayPeriod.pm ? "PM" : "AM";
});
}
}
//code inside build(BuildContext context)
InkWell(
onTap: () {
_selectTime();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${f.format(_time.hourOfPeriod)}:"),
Text("${f.format(_time.minute)}"),
Text("$hourOfPeriod")
],
),
)
//Output Format: HH:MM AM/PM

Show the weekdays of every week of a month flutter

How can I only Display the Date and the day without the time in flutter. And I want a list of only a week of a month displayed and when the week end, the next round of week will be displayed. Also, when I push a button in one value of a list everything will be the same and all of the button will disappear, I just want to edit one line, can someone please help me.
any answer is appreciated. thank you.
DateFormat formatter = DateFormat('MM/dd (E)');
final items = List.generate(7, (i) {
DateTime date = DateTime.now();
return formatter.format(date.add(Duration(days: i)));
});
body:
Column(children: <Widget>[
Text('Humpty Dumpty', style: TextStyle(fontSize: 30.0,fontWeight: FontWeight.bold),),
Expanded( child:
ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, index) {
return ListTile(
title: Wrap (
spacing: 20, // to apply margin in the main axis of the wrap
runSpacing: 20, // to apply margin in the cross axis of the wrap
children: <Widget>[Text('${items[index]}'),Text('${text.toString()}')]),
trailing:
Visibility(
visible: viewVisible,
child: ElevatedButton(
child: Text('登 録'),
style: ElevatedButton.styleFrom(primary: Colors.indigo[700],
), onPressed: () {
if (viewVisible) {
ButtonClicked();
}
_awaitReturnValueFromSecondScreen(context);
},
)),
);
},
)
)
]
),
);
}
Try below code without using third package library
DateTime today = new DateTime.now();
String date =
"${today.day.toString().padLeft(2, '0')}/${today.month.toString().padLeft(2, '0')}/${today.year.toString()}";
//print your date
print(date);
your output => 27/08/2021
with using third package
0
You should add DateFormat intl: ^0.17.0 dependency here in your pubspec.yaml file
DateTime now = DateTime.now();
String formattedDate = DateFormat('dd-MM-yyyy').format(now);
print(formattedDate);
Your output look like this : 27-08-2021
you can use intl package to format date.
int package link: https://pub.dev/packages/intl/install
and use it like this:
import 'package:intl/intl.dart';
main() {
final DateFormat df= DateFormat('yyyy-MM-dd');
final String formated= df.format(DateTime.now());
print(formated); // print 2021-08-27
}
also you can use code like this:
print(DateFormat.yMMMd().format(DateTime.now()));
for more details read this:
https://api.flutter.dev/flutter/intl/DateFormat-class.html

How to display time on buttons in Flutter

Requirement:
I have 2 buttons, I want when I click on button 1 its text should be replaced by the current time, and the same for button 2.
Problem:
The problem is when I click on button 1 its text change to the current time, but when I click on button 2 after a few minutes its text changes to the same time that button 1 has.
Here is my code:
void initState() {
// TODO: implement initState
super.initState();
_getTime();
}
void _getTime() {
final String formattedDateTime =
DateFormat('kk:mm:ss').format(DateTime.now()).toString();
setState(() {
getTime = formattedDateTime;
print(getTime[0]);
});
}
var timeInText="Time in";
var timeOutText="Time out";
\\button 1
RoundedButton(icon: Icon(Icons.timer,color: Colors.white),
text:timeInText,
bgcolor: Colors.blue[500],
press:(){
setState(() {
timeInText=getTime;
});
})
//button 2
RoundedButton(icon: Icon(Icons.timer,color: Colors.white),
text:timeoutText,
bgcolor: Colors.blue[500],
press:(){
setState(() {
timeoutText=getTime;
});
})
please help to fix it. thanks
You call _getTime() only in initState. Time is stored on initialization and never updated after that. Since it's never updated it's showing the same time constantly.
To fix that add a _getTime() call to both of your onPressed functions like this:
onPressed: () {
_getTime();
setState(() {
timeoutText = getTime;
});
}),
You get the time one, when the button clicked. You have to write your method codes in setState too i think. And get the current time 🤔 i hope it will help

TimePicker output not showing the picket time correctly

I need to get a time from a timepicker and show it on a text widget.
Here you have the widget that should show the time:
pickedTime = TimeOfDay.now();
ListTile(
title: Text(
" ${pickedTime.hour}:${pickedTime.minute}"),
trailing: Icon(Icons.timer,size: 45,),
onTap: _pickTime,
),
And here you have the function _pickTime:
_pickTime() async{
TimeOfDay time = await showTimePicker(
context: context,
initialTime: pickedTime);
setState(() {
pickedTime = time;
});
}
I have detected an issue when the picked time hour or minute is smaller than 10, the output is as shown in the picture for 04:05:
I would like to show the picked time always in format HH:mm.
The following is an extension on the int class that you can use to enforce two characters for each part of the time:
extension TwoChar on int {
String toTwoChars() {
return this.toString().padLeft(2, '0');
}
}
Then modify your code to use the extension:
title: Text("${pickedTime.hour.toTwoChars()}:${pickedTime.minute.toTwoChars()}"),

make Button/Widget appear for X days or specific period from Date_X to Date_Z

I'm trying to add (FloatingActionButton) appear for X days or a specific period from Date_X to Date_Z
I think it should be something like this
if ((DateTime.now =< DateTime.utc(2021,4,1)) && (DateTime.now => DateTime.utc(2021,5,1))){FloatingActionButton()}
I know there is a DateTimeRange class in flutter but I couldn't make it work.
So could anyone help with this?
Thanks
At first, declare four variable
bool _isStaisfied = false;
DateTime _now = new DateTime.now();
DateTime _startRange; // asign your Date;
DateTime _endRange; // asign your Date;
and in initstate(), compare them,and assign _isSatisfied value based upon them,
#override
void initState() {
print("helllo ");
if (_now.isAfter(_startRange) && _now.isBefore(_endRange)) { // apply condition as you requirement
setState(() {
_isStaisfied = true;
});
}
super.initState();
}
and apply Condition in scaffold
floatingActionButton: _isStaisfied ? FloatingActionButton(
onPressed: null,
tooltip: 'Increment',
child: Icon(Icons.add),
) : null,
though this is not best practice, but will save the day!