Flutter how to show current date and next 5 day dates? - flutter

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"

Related

Limit range of selected days in datepicker fluttter

I'm building booking application and currently I'm facing this issue where the use can select a range of days using ShowDateRangePicker, showDateRangePicker, however the use can select any range within the start and end dates but I'm asked to not let user select more than 14 days. For Example:
Startdate = 12/2/2023
endDate = 1/1/2024
and the user selected range: 12/2/2023 - 28/2/2023
In this case it should throw an error because the range exceeded the limit of 14 days. the difference in range exceeded 14.
Or a better one when the user reach a from date + 14 it will stop allowing them to select more days.
You can use syncfusion_flutter_datepicker library. It has a selectionChanged callback that you can manipulate to limit selectable dates on the go. The snippet below shows how to limit the range to 14 days from selected _start day.
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
final DateTime _minDate = DateTime.now();
DateTime _maxDate = DateTime.now().add(const Duration(days: 365));
final Duration _duration = const Duration(days: 14);
DateTime _start = DateTime.now();
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SfDateRangePicker(
minDate: _minDate,
maxDate: _maxDate,
selectionMode: DateRangePickerSelectionMode.range,
onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
if (args.value is PickerDateRange) {
_start = (args.value as PickerDateRange).startDate!;
setState(() {
// limit the maxDate to 14 days from selected date
_maxDate = _start.add(_duration);
});
}
},
)),
);
}
}
For more customization refer to docs.

How to sort by date in flutter List.generate?

In List component we have this method.
List<Widget> generateList(goalList) {
return List.generate(
goalList.length,
(int index) {
return GoalCardBase(
goalId: goalList.id,
child: GoalCardData(goal: goalList[index]),
);
},
);
}
i am trying to sort them by startDate. I was looking a solution everyone suggest something like that.
goalList.sort((a, b)=> a.compareTo(b['objectiveStartDate']));
but from goalList I could not reach the start date. Maybe i am completly wrong.
What would you do if you were to solve this problem?
The whole code
import 'package:app/src/common.dart';
import 'package:app/src/common_widgets/app_buttons.dart';
import 'package:app/src/features/goals/card/goal_card_base.dart';
import 'package:app/src/features/goals/card/goal_card_data.dart';
import 'package:app/src/utils/utils.dart';
import 'package:go_router/go_router.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
class GoalsPageBodyGoals extends StatelessWidget {
final List<Widget> data;
const GoalsPageBodyGoals({Key? key, required this.data}) : super(key: key);
List<Widget> generateList(goalList) {
return List.generate(
goalList.length,
(int index) {
return GoalCardBase(
goalId: goalList.id,
child: GoalCardData(goal: goalList[index]),
);
},
);
}
#override
Widget build(BuildContext context) {
return Column(children: [
...data,
const SizedBox(height: 24),
Column(
key: const Key('goals_page_action_buttons'),
children: [
AppButtons.button(
onPressed: () => context.go('/add-goal'),
child: Text(context.l10n.goalsListPrimaryButtonText)),
AppButtons.textButton(
onPressed: () => AppUtils.snackBarNotImplemented(context),
phosphorIcon: PhosphorIcons.arrowRight,
child: Text(context.l10n.goalsListTextLink))
],
),
]);
}
}
IN goal Objective (GoalCardData(goal: goalList[index]),) I have attributes(title, startDate, amount, salary etc.) , so when we create a goal it has date. But when i list them its just randomly saving.
Try sorting the list before rendering/returning it in the code.
goalList.sort((b, a) => a['startDate'].compareTo(b['startDate']);
This is the code I tried on dartpad and it works:
void main(){
cls _cls = cls("title",DateTime.now());
cls cls2 = cls("title2",DateTime.now().subtract(Duration(days:1)));
List<cls> clist = [_cls,cls2];
for(var v in clist){
print(v.startDate.toString());
}
clist.sort((a,b) => a.startDate!.compareTo(b.startDate!));
for(var v in clist){
print(v.startDate.toString());
}
}
class cls{
String? title;
DateTime? startDate;
cls(this.title,this.startDate);
}
So, in your generateList function, before returning, you can do this:
goalList.sort((a,b) => a.startDate.compareTo(b.startDate));

How can I get all days (name, number) of 4 weeks from current day (in the future)?

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");

How to put two millisec convert dates in my code

Is this way of coding correct, and how do show 2 dates. Can someone help me to check and correct my coding? int ts=1646274840000; int ts2=1646015654686;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'api_service.dart';
class AppoinmentList extends StatefulWidget {
final String? token;
AppoinmentList({
Key? key,
this.token
}) : super(key: key);
#override
_AppoinmentListState createState() => _AppoinmentListState();
}
class _AppoinmentListState extends State<AppoinmentList> {
#override
void initState() {
super.initState();
APIService.getAppointmentList(widget.token!);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Appointment Listing"),
),
body: _time()
);
//body: _appoinmentListUI(),
}
}
_time() {
int ts=1646274840000;
int ts2=1646015654686;
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(ts);
DateTime ts2date = DateTime.fromMillisecondsSinceEpoch(ts2);
String fdatetime = DateFormat('MM/dd/yyyy, hh:mm a').format(tsdate);
String fdatetime2 = DateFormat('MM/dd/yyyy, hh:mm a').format(ts2date);
return Container(
child: Text(fdatetime,),
);
}
I only success to show the output for one date only. How to show two dates? Someone can help me.
This output show for one date only
_time() only returns one Text widget for the first date. You need to add another one for the second date.
Put both Text widgets in a Column if you want them on top of each other.
like this:
_time() {
int ts = 1646274840000;
int ts2 = 1646015654686;
DateTime tsdate = DateTime.fromMillisecondsSinceEpoch(ts);
DateTime ts2date = DateTime.fromMillisecondsSinceEpoch(ts2);
String fdatetime = DateFormat('MM/dd/yyyy, hh:mm a').format(tsdate);
String fdatetime2 = DateFormat('MM/dd/yyyy, hh:mm a').format(ts2date);
return Column(
// To make children align to the left of the screen
crossAxisAlignment: CrossAxisAlignment.start,
// to prevent `Column` from expanding.
mainAxisSize: MainAxisSize.min,
children: [
Text(fdatetime),
Text(fdatetime2),
],
);
}

The argument type 'String' can't be assigned to the parameter type 'List<Widget>'

Dart
>I having problems in my first personal expense app.in that I make chart of daily expense in their I face this problem. please gibe me right solution about that problem
import 'package:flutter/material.dart';
import './transaction.dart';
import 'package:intl/intl.dart';
class Chart extends StatelessWidget {
final List <Transaction> recenttransaction;
Chart(this.recenttransaction);
List <Map<String,Object>> get groupedTransactionValues{
return List.generate(7, (index) {
final weekday = DateTime.now().subtract(Duration(days: index),);
var totalSum = 0.0;
for(var i=0 ; i<recenttransaction.length;i++){
if(recenttransaction[i].date.day == weekday.day &&
recenttransaction[i].date.month == weekday.month &&
recenttransaction[i].date.year == weekday.year){
totalSum += recenttransaction[i].amount;
}
}
// print(DateFormat.E().format(weekday));
// print(totalSum);
return {"day":DateFormat.E().format(weekday).substring(0,1),"amount":totalSum};
});
}
#override
Widget build(BuildContext context) {
// print(groupedTransactionValues);
return Card(
elevation: 6,
margin: EdgeInsets.all(20),
child: Row(
**Error part**
children: groupedTransactionValues.map((data){
return Text('${data['data']} : ${data['amount']}');
}).toString(),
));
}
}
change
children: groupedTransactionValues.map((data){
return Text('${data['data']} : ${data['amount']}');
}).toString(),
to
children: groupedTransactionValues.map((data){
return Text('${data['data']} : ${data['amount']}');
}).toList(),