How to put two millisec convert dates in my code - flutter

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

Related

I can't get the country code in Flutter. Everything is either us or en

I can't get the country code in Flutter. Everything is either us or en.
It shows up as us or en even if I change the device's region or language. I want to show the language and region registered on the user's device.
#override
Widget build(BuildContext context) {
Locale locale = Localizations.localeOf(context);
String? localeCode = locale.countryCode;
String? languageCode = locale.languageCode;
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: [
HomeScreen(localeCode, languageCode),
],
),
);
}
class PomodoroPage extends StatefulWidget {
PomodoroPage(this.localeCode, this.languageCode);
final String? localeCode;
final String? languageCode;
#override
_PomodoroPageState createState() => _PomodoroPageState();
}
import 'dart:io';
String localeName = Platform.localeName;

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

Sometimes variable changes, sometimes it doesn't

first of all, sorry for the lack of information in the title, I just couldn't think of anything better to write.
My problem is that I'm parsing JSON data from an online API and sometimes it displays what I want it to display, and sometimes it doesn't... here is the code:
(The first code block is the class of what I'll be using in the second block, which is the important part and probably where I think the problem is coming from)
import 'dart:convert';
import 'package:http/http.dart' as http;
class CanteenInfo {
final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
List canteenMenu = [];
var data;
String workingHours = "yes";
CanteenInfo() {
getWebsiteData();
}
Future getWebsiteData() async {
var response = await http.get(Uri.parse(canteenUrl));
if (response.statusCode == 200) {
data = json.decode(response.body);
workingHours = data[3]["horario"];
print("Hours: " + workingHours);
}
else {
throw Exception('Failed to read $canteenUrl');
}
}
}
class WorkingHours extends StatefulWidget {
const WorkingHours({Key? key}) : super(key: key);
#override
State<WorkingHours> createState() => _WorkingHours();
}
class _WorkingHours extends State<WorkingHours> {
String hours = "yes";
CanteenInfo canteen = CanteenInfo();
void getHours() {
setState(() {
hours = canteen.getHours();
});
}
#override
Widget build(BuildContext context) {
getHours();
return Scaffold(
appBar: AppBar(
title: Text('EasyFood'),
),
body: Center(
child: Container (
margin: const EdgeInsets.only(top: 100),
child: Column(
children: <Widget>[
Text(
'Lunch: ' + hours,
style: const TextStyle(
fontSize: 20
)
),
],
),
),
),
);
}
}
If I haven't made my problem clear, when I run the code, sometimes it displays the text as "Lunch: yes" and sometimes as the correct thing, which is "Lunch: 11:30 às 14:00".
By my understanding, I think what's happening is that sometimes the code can get the API information and time and has time to change the variable before the page loads, and sometimes it doesn't. Either way, I don't know how to fix it so if anyone has any idea I would relly appreciate the help :)
Thanks alot for taking the time to read this
I'm not sure if getHours method exists in CanteenInfo.
But you probably need to override initState method in your stateful widget and call
canteen.getWebsiteData().then((value) {
setState(() => hours = canteen.workingHours);
});
or something like that depending on which method returns data from API
A good decision will be to wait CanteenInfo object "canteen" to be initialized, smth like this:
var flag = false;
loadData()async{
flag = true;
canteen = CanteenInfo();
await getHours();
setState((){flag=false;});
}
Widget build(BuildContext context) {
if (hours == "yes" && !flag)
loadData();
if (flag)
return Scaffold(body:CircularProgressIndicator());
return Scaffold(
appBar: AppBar(
title: Text('EasyFood'),
),
body: Center(
child: Container (
margin: const EdgeInsets.only(top: 100),
child: Column(
children: <Widget>[
Text(
'Lunch: ' + hours,
style: const TextStyle(
fontSize: 20
)
),
],
),
),
),
);
}
I'm not sure if class object initialization works correct here, maybe you also need to add async/await
class CanteenInfo {
final String canteenUrl = 'https://sigarra.up.pt/feup/pt/mob_eme_geral.cantinas';
List canteenMenu = [];
var data;
String workingHours = "yes";
getWebsiteData() async {
var response = await http.get(Uri.parse(canteenUrl));
if (response.statusCode == 200) {
data = json.decode(response.body);
workingHours = data[3]["horario"];
print("Hours: " + workingHours);
}
else {
throw Exception('Failed to read $canteenUrl');
}
}
getHours() {
return workingHours;
}
}
// ------------------------
class WorkingHours extends StatefulWidget {
const WorkingHours({Key? key}) : super(key: key);
#override
State<WorkingHours> createState() => _WorkingHours();
}
// ------------------------
class _WorkingHours extends State<WorkingHours> {
String hours = "yes";
CanteenInfo canteen = CanteenInfo();
#override
void initState() {
super.initState();
canteen.getWebsiteData().then(() {
hours = canteen.getHours();
});
}
}

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

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"

How to pass variables to a StatefulWidget: This class is marked as '#immutable'

I am calling a class (Titletext) that returns a row and while it works in my emulator the editor is giving me a warning so I am trying to figure out the proper way to handle this as the editor is displaying a warning.
I tried using a Stateless widget but it is supposed to accept values so that wouldn't work, I have tried google and here as well and while there are a good amount of posts on "This class (or a class which this class inherits from) is marked as '#immutable'" it doesn't really help me understand why what I'm doing is incorrect. When I add the final keyword, my constructor gets angry since my variables are then supposed to be final.
import 'package:flutter/material.dart';
import './header.dart';
import './title.dart';
class NotificationsScreen extends StatefulWidget {
createState() {
return NotificationsScreenState();
}
}
class NotificationsScreenState extends State<NotificationsScreen> {
String searchString = '';
Widget header = new Header();
Widget title = new TitleText(Icons.notifications, 'Notifications');
//team logo centered
//List of notifications
Widget build(context) {
return Container(
margin: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Column(
children: [
header,
Container(margin: EdgeInsets.only(top: 25.0)),
title,
],
),
);
}
}
import 'package:flutter/material.dart';
class TitleText extends StatefulWidget {
IconData icon = IconData(0);
String title = '';
TitleText(this.icon, this.title);
#override
_TitleState createState() => _TitleState();
}
class _TitleState extends State<TitleText> {
#override
Widget build(context) {
return Container(
width: double.infinity,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(widget.icon, size: 30),
Text(widget.title),
],
),
);
}
}
The output works as intended but with the warning I am clearly handling this wrong, I am looking for the way I should be passing values to a class like this that returns a widget.
Like the annotation says, all properties of a Widget subclass must be immutable/final.
As such, if you want to give your properties a default values, you have to do so in the constructor.
Instead of:
class Foo {
String bar = "default";
Foo({this.bar});
}
do:
class Foo {
final String bar;
Foo({this.bar = "default"});
}
or:
class Foo {
final String bar;
Foo({String bar}): bar = bar ?? "default";
}