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
Related
I want to get all days 4 weeks from my current day. For example, today is June (Thu, 23), I want to get (24, Fri) .... up until (21, Thu) July.
You can generate days like
late List<DateTime> days = List.generate(
7 * 4, // 4weeks
(index) => DateTime.now().add(
Duration(days: index+1),
),
);
And to get days name I am using intl package. and formatter is
final formatter = DateFormat('EEEE');
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: days.length,
itemBuilder: (context, index) => Text(
"name: ${formatter.format(days[index])} number:${days[index].day} "),
),
);
}
Using DateFormat
final DateFormat formatter = DateFormat('MMMMd');
_nextDateFormatted = formatter.format(widget.nextDate);
In your case, you will have 4 dates. Heres with the first date
_firstDateFormatted = formatter.format(DateTime.now().add(days:1).millisecondsSinceEpoch)
List<dynamic> data = [];
for (int i = 1; i < 29; i++) {
data.add(DateFormatters()
.dMy
.format(DateTime.now().add(Duration(days: i))));
}
log("$data");
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
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,),
),
]
I need to show current date and month Also next 5 days date and month in a text widget.
Simply like this
Column(
children: [
Text('09'),
Text('Nov')
],
)
I need to show in a row that today date or month and the next 5 days date and month. Any guide in code how can i do this thing?
Expected output is
28NOV, 29NOV, 30NOV, 1Dec, 2Dec
A simple example. No styles applied, adjust to your needs.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class MyScreen extends StatefulWidget {
#override
_MyScreenState createState() => _MyScreenState();
}
class _MyScreenState extends State<MyScreen> {
final _currentDate = DateTime.now();
final _dayFormatter = DateFormat('d');
final _monthFormatter = DateFormat('MMM');
#override
Widget build(BuildContext context) {
final dates = <Widget>[];
for (int i = 0; i < 5; i++) {
final date = _currentDate.add(Duration(days: i));
dates.add(Column(
children: [
Text(_dayFormatter.format(date)),
Text(_monthFormatter.format(date)),
],
));
}
return Scaffold(
appBar: AppBar(
title: Text('Tests'),
),
body: Row(
children: dates.map((widget) => Expanded(child: widget)).toList(),
),
);
}
}
Also the default month names from the intl library are used.
You might need to adjust the code for i18n.
List months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
DateTime today = DateTime.now();
var currentDate = today.day;
var monthOfCurrentDate = months[today.month +1];
DateTime futureDate = DateTime.now().add(Duration(days: 5));
var dayOfFutureDate = futureDate.day;
var monthOfFutureDate = months[futureDate.month+1];
You can use like this,
Column(
children: [
Text(currentDate.toString()),
Text(monthOfCurrentDate)
],
)
and you can format time as below, using flutter intl package intl package on pub.dev
DateFormat.MMMd().format(today) // this will output as "17 Nov"
I'm trying to allow a user to mark an item being built by a ListViewBuilder as a favorite. With my current code, when a user favorites one episode, all episodes are marked as favorite. I would like the user to be able to add each episode individually as a favorite and persist that favorite after a restart. I have the data saved to a firebase database but it seems like this should be handled in the app itself.
What is the best way to do this? Thanks!
Here is my current code:
class Epi {
final String endTime;
final String name;
final String networkName;
final String showName;
final String startTime;
Epi({this.endTime, this.name, this.networkName, this.showName, this.startTime});
factory Epi.fromJson(Map<dynamic, dynamic> parsedJson) {
DateTime endTimeCon = DateTime.parse(parsedJson['endTime']);
String newEndTime = formatDate(endTimeCon, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am]);
DateTime startTimeCon = DateTime.parse(parsedJson['startTime']);
String newStartTime = formatDate(startTimeCon, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am]);
return Epi(
endTime: newEndTime,
name: parsedJson['name'],
networkName: parsedJson['networkName'],
showName: parsedJson['showName'],
startTime: newStartTime,
);
}
}
bool _isFavorited = true;
void _toggleFavorite() {
setState(() {
if (_isFavorited) {
_isFavorited = false;
} else {
_isFavorited = true;
}
});
}
body: Column(
children: <Widget>[
SizedBox(height: 5.0),
Expanded(
child: ListView.builder(
itemCount: elist.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
selectEpisode(index);
},
child: Card(
child: Column(
children: <Widget>[
ListTile(
title: Text(elist[index].name),
subtitle: Text(elist[index].startTime),
leading: IconButton(
icon: (_isFavorited ? Icon(Icons.favorite_border) : Icon(Icons.favorite)),
color: Colors.red[500],
onPressed: _toggleFavorite,
),
trailing: Icon(Icons.arrow_forward_ios)
)
],
),
),
);
}),
),
],
)
In my Congress Fahrplan App (Github) I'm doing exactly what you want to achieve.
In favorite_provider I store the value in the object itself and add it to my list of favorited objects. Whenever an object is added to this list, the list is written to the disk as JSON with my file_storage class.
When the app is restarted, the objects are fetched from a REST API. Then I match their IDs with the objects from the local JSON and set whether they are favorited or not to restore the favorite state.
Making a favorite list of items basically differs based on the app design and you might as well develop your own logic for this purpose. Now, while what #benjaminschilling33 posted is true, you can also achieve this in a simple way.
What I would do is, add a boolean called isFavorite on the constructor like this:
class Epi {
final String endTime;
final String name;
final String networkName;
final String showName;
final String startTime;
bool isFavorite;
}
//initialize the isFavorite to false cause no item in your list is is favorite at the beginning
Epi({this.endTime, this.name, this.networkName, this.showName, this.startTime, this.isFavorite=false});
//lets create a list _episode which contains all the movie for demonstration purpose
List<Epi> _episode = [Epi(initialized data)];
//create a getter for the list
List<Epi> get episode{
return _episode.where((Epi episode) => episod.isFavorite).toList(); //this will return a list where the isFavorite is true
}
//You can then set your icon (in the list-tile) based on your isFavorite result
ListTile(
...
icon: Icons(elist[index].isFavorite?Icon(Icons.favorite):Icon(Icons.favorite_border);
)
//Then adjust the logic on your onPress
onPressed: (){
setState((){
elist[index].isFavorite=!elist[index].isFavorite //this will vary from true to false and vice versa when pressed
});
}
This is the simplest way to add list of items that is favorited by the user rather than building another list for the favorite section. What I wrote here is offline based test you can achieve and the key take away is the where property which is:
List<Epi> episode=[some data]
epsode.where((Epi episode)=>episode.isFavorite).toList();
You can use this method even after deploying your app to the cloud database by creating that attribute in your database based on the user's id.