How to access data inside class - flutter

I'm trying to convert a timestamp I get from a network call and display it as regular time and date in my app. But I cant access the "int timestamp" from its class.
import 'package:intl/intl.dart';
int timeInMillis = **timestamp**; // I'm trying to get the timestamp here !!
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat('HH:mm - dd.MM.yyyy').format(date);
class Posts {
final String result;
final int timestamp;
final String time;
Posts({this.timestamp, this.result, this.time});
factory Posts.fromJson(Map<String, dynamic> json) {
return Posts(
result: json['result'],
timestamp: json['timestamp'],
time: formattedDate,
);
}
}

You need to convert the value from json using int.parse('1610515846')
import 'package:intl/intl.dart';
int timeInMillis = **timestamp**; // I'm trying to get the timestamp here !!
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat('HH:mm - dd.MM.yyyy').format(date);
class Posts {
final String result;
final int timestamp;
final String time;
Posts({this.timestamp, this.result, this.time});
factory Posts.fromJson(Map<String, dynamic> json) {
return Posts(
result: json['result'],
timestamp: int.parse(json['timestamp']),
time: formattedDate,
);
}
}

Related

jsonEncode generating error while converting object to jsonstring in flutter

For explaining what I am facing problem while creating a jsonstring from object list,I have created this basic demo,
actually I am trying to create a backup file for saving records but I am getting an error while jsonEncode.
getting following error
Converting object to an encodable object failed: Instance of 'TransactionModel'
class TransactionModel {
String id;
bool isexpense;
DateTime date;
double amount;
TransactionModel({
this.amount = 0.00,
required this.id,
this.isexpense = true,
required this.date,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'isexpense': isexpense,
'date': date,
'amount': amount,
};
}
}
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
String result = jsonEncode(trans);//error bcz of jsonEncode
print(result);
}
You can't encode an object with custom property like DateTime, you need first convert it to map, then encode it, try this:
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
var listOfMap = trans.map((e) => e.toJson()).toList();
String result = jsonEncode(listOfMap);
print(result);
}

The named parameter 'time' is required, but there's no corresponding argument. Try adding the required argument flutter problem?

In order to get weather Data using OpenWeatherMap API, I created a Weather class as shown in the code below:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
const appId = "d8cdd9eca073d9bbf5ef49405cbf50e8";
class Weather {
final int max;
final int min;
final int current;
final String name;
final String day;
final int wind;
final int humidity;
final int chanceRain;
final String image;
final String time;
final String location;
Weather(
{
required this.max,
required this.min,
required this.name,
required this.day,
required this.wind,
required this.humidity,
required this.chanceRain,
required this.image,
required this.current,
required this.time,
required this.location
});
}
Then, I created the method fetchData to get the current temp, today & tomorrow weather and 7 day weather as shown below:
Future<List> fetchData(String lat,String lon,String city) async{
var url = "https://api.openweathermap.org/data/2.5/onecall?lat=$lat&lon=$lon&units=metric&appid=$appId";
var response = await http.get(Uri.parse(url));
DateTime date = DateTime.now();
if(response.statusCode==200){
var res = json.decode(response.body);
//current Temp
var current = res["current"];
Weather currentTemp = Weather(
current: current["temp"]?.round()??0,
name: current["weather"][0]["main"].toString(),
day: DateFormat("EEEE dd MMMM").format(date),
wind: current["wind_speed"]?.round()??0,
humidity: current["humidity"]?.round()??0,
chanceRain: current["uvi"]?.round()??0,
location: city,
image: findIcon(current["weather"][0]["main"].toString(), true)
);
//today weather
List<Weather> todayWeather = [];
int hour = int.parse(DateFormat("hh").format(date));
for(var i=0;i<4;i++){
var temp = res["hourly"];
var hourly = Weather(
current: temp[i]["temp"]?.round()??0,
image: findIcon(temp[i]["weather"][0]["main"].toString(),false),
time: Duration(hours: hour+i+1).toString().split(":")[0]+":00"
);
todayWeather.add(hourly);
}
//Tomorrow Weather
var daily = res["daily"][0];
Weather tomorrowTemp = Weather(
max: daily["temp"]["max"]?.round()??0,
min:daily["temp"]["min"]?.round()??0,
image: findIcon(daily["weather"][0]["main"].toString(), true),
name:daily["weather"][0]["main"].toString(),
wind: daily["wind_speed"]?.round()??0,
humidity: daily["rain"]?.round()??0,
chanceRain: daily["uvi"]?.round()??0
);
//Seven Day Weather
List<Weather> sevenDay = [];
for(var i=1;i<8;i++){
String day = DateFormat("EEEE").format(DateTime(date.year,date.month,date.day+i+1)).substring(0,3);
var temp = res["daily"][i];
var hourly = Weather(
max:temp["temp"]["max"]?.round()??0,
min:temp["temp"]["min"]?.round()??0,
image:findIcon(temp["weather"][0]["main"].toString(), false),
name:temp["weather"][0]["main"].toString(),
day: day
);
sevenDay.add(hourly);
}
return [currentTemp,todayWeather,tomorrowTemp,sevenDay];
}
return [null,null,null,null];
}
I got the following problems:
The named parameter 'time' is required, but there's no corresponding argument.
Try adding the required argument.
The named parameter 'max' is required, but there's no corresponding argument.
Try adding the required argument.
The named parameter 'day' is required, but there's no corresponding argument.
Try adding the required argument.
And the round() function seems like it doesn't work!
If you mark those as required, you need to provide any time you use the Weather(...) constructor, you can't ignore those parameters.
If you want to have those as optional, you need to remove the required keyword, but you get the error because a non-nullable value can't be null.
In order to have a nullable value you need to postpone a ? at the end of your variable type for example
String -> non nullable String
String? -> nullable String
so if you want to be able to define only some of the parameter you need to change your class this way
class Weather {
final int? max;
final int? min;
final int? current;
final String? name;
final String? day;
final int? wind;
final int? humidity;
final int? chanceRain;
final String? image;
final String? time;
final String? location;
Weather(
{
this.max,
this.min,
this.name,
this.day,
this.wind,
this.humidity,
this.chanceRain,
this.image,
this.current,
this.time,
this.location,
});
}
Of course this will be not enough, because you may want to have either optional and required parameters, but you can discover more about sound null safety here: https://dart.dev/null-safety

How to get SQFlite data date wise in flutter?

I'm creating todo app in flutter. And I need to show Todos date wise. Like all Todos created today should shown under Today, all the tomorrow's Todos should shown under Tomorrow.
I have created my table like this:
database.execute("""
CREATE TABLE Todotable(
id INTEGER PRIMARY KEY AUTOINCREMENT,
taskName TEXT NOT NULL,
taskTag TEXT NOT NULL,
date TEXT NOT NULL,
isReminder INTEGER NOT NULL,
isCompleted INTEGER NOT NULL
)
""");
I don't know how to query SQFlite data date wise and format it like Today and Tomorrow. And show in section like today and tomorrow as shown in design.
Thanks for answers:)
for getting todos for tomorrow
//for tomorrow
String tomorrowDate= DateTime.now().add(Duration(days: 1)).toIso8601String();
var todosForTomrrow= await database
.rawQuery('SELECT * FROM Todotable WHERE date = ?', [tomorrowDate]);
//for today
String todayDate= DateTime.now().toIso8601String();
var todosForToday= await database
.rawQuery('SELECT * FROM Todotable WHERE date = ?', [todayDate]);
Date is converted and saved here in string format and date should converted to same format before inserting into the table like this
You can create DATETIME columns in sqflite.
Here is an example for a Weather table created in a sqflite database:
batch.execute('''
CREATE TABLE $tableWeather (
$weatherLocalization TEXT NOT NULL,
$weatherDate DATETIME NOT NULL,
$weatherHumidityPercentage REAL,
$weatherWindDegree REAL,
$weatherWindSpeed REAL,
$weatherPressureHPascal INTEGER,
$weatherTemperatureCelsius REAL,
$weatherDescription TEXT,
$weatherIconId TEXT,
PRIMARY KEY($weatherLocalization, $weatherDate));
''',);
You can create a Weather object as follows:
class Weather{
String localization;
DateTime date;
double humidityPercentage;
double windDegree;
double windSpeedMS;
int pressureHPascal;
double temperatureCelsius;
String description;
String iconId;
Weather({
#required this.localization,
#required this.date,
this.humidityPercentage,
this.windDegree,
this.windSpeedMS,
this.pressureHPascal,
this.temperatureCelsius,
this.description,
this.iconId
});
//to be used when inserting a row in the table
Map<String, dynamic> toMap() {
final map = new Map<String, dynamic>();
map["$weatherLocalization"] = localization;
map["$weatherDate"] = date.toString();
map["$weatherHumidityPercentage"] = humidityPercentage;
map["$weatherWindDegree"] = windDegree;
map["$weatherWindSpeed"] = windSpeedMS;
map["$weatherPressureHPascal"] = pressureHPascal;
map["$weatherTemperatureCelsius"] = temperatureCelsius;
map["$weatherDescription"] = description;
map["$weatherIconId"] = iconId;
return map;
}
//to be used when converting the row into object
factory WeatherOnDate.fromMap(Map<String, dynamic> data) => new WeatherOnDate(
localization: data["$weatherLocalization"],
date: DateTime.parse(data["$weatherDate"]),
humidityPercentage: data["$weatherHumidityPercentage"],
windDegree: data["$weatherWindDegree"],
windSpeedMS: data["$weatherWindSpeed"],
pressureHPascal: data["$weatherPressureHPascal"],
temperatureCelsius: data["$weatherTemperatureCelsius"],
description: data["$weatherDescription"],
iconId: data["$weatherIconId"]
);
}
Be careful to transform your DateTime attribute to a String or int as I did in the toMap() function.
Then, when you want to fetch a date you can do this:
Future<Weather> fetchWeatherOnDate(DateTime dateTime) async {
DatabaseHelper _databaseHelper = Injection.injector.get();
List<Map<String, dynamic>> weatherMaps = await _databaseHelper.db.rawQuery(
'SELECT * FROM $tableWeather WHERE DATE($weatherDate) = DATE(?)',
[dateTime.toString()]);
List<Weather> weathers= [];
for (final weatherMap in weatherMaps) {
weathers.add(Weather.fromMap(weatherMap));
}
if (weathers.isNotEmpty){
return weathers[0];
}
return null;
}
DateTime today = DateTime.now()
Weather weatherToday = fetchWeatherOnDate(today);
I think that it gives you a good idea of how to solve your problem :)
DateTime is not supported in Flutter SQLite package.
Check the information about supported SQLite types:
https://pub.dev/packages/sqflite#supported-sqlite-types
DateTime is not a supported SQLite type. Personally I store them as int (millisSinceEpoch) or string (iso8601)
We can use String or int as suggested from the package developer.
To work with a conditional selection of items of day in DB, perhaps a String is more convenient.
Personally, I prefer user formatter to get the search keyword, as shown below:
DateFormat formater = DateFormat('yyyyMMdd');
var today = formater.format(DateTime.now());
var tomorrow = formater.format(DateTime.now().add(const Duration(days: 1)));
To search in DB, I'd use a method like below:
Future<TodoList?> getTodoListByDay(String day) async {
final db = await database;
String sql =
"SELECT * FROM Todotable WHERE date = \'${day}\' ";
var res = await db.rawQuery(sql);
List<TodoList> objs = res.isNotEmpty
? res.map((c) => TodoList.fromMap(c)).toList()
: [];
return objs.isNotEmpty ? objs : null;
}
TodoList class could be generate from json, as I do with 'jsonToDartModel' package.
import 'dart:convert';
class TodoList {
int? id;
String? taskName;
String? taskTag;
String? date;
int? isReminder;
int? isCompleted;
TodoList({
this.id,
this.taskName,
this.taskTag,
this.date,
this.isReminder,
this.isCompleted,
});
factory TodoList.fromMap(Map<String, dynamic> data) => TodoList(
id: data['id'] as int?,
taskName: data['taskName'] as String?,
taskTag: data['taskTag'] as String?,
date: data['date'] as String?,
isReminder: data['isReminder'] as int?,
isCompleted: data['isCompleted'] as int?,
);
Map<String, dynamic> toMap() => {
'id': id,
'taskName': taskName,
'taskTag': taskTag,
'date': date,
'isReminder': isReminder,
'isCompleted': isCompleted,
};
/// `dart:convert`
///
/// Parses the string and returns the resulting Json object as [TodoList].
factory TodoList.fromJson(String data) {
return TodoList.fromMap(json.decode(data) as Map<String, dynamic>);
}
/// `dart:convert`
///
/// Converts [TodoList] to a JSON string.
String toJson() => json.encode(toMap());
}

How to sort a DateTime list in Flutter

I fetch data from firebase and I want to sort the date data I receive by date. The object I receive look like the following:
Appointment Model
class MAppointment with ChangeNotifier {
String id;
String title;
String location;
DateTime createdAt;
String email;
List<Events> events;
List<Participants> participants;
String nameOriginater;
MAppointment({
this.id,
this.title,
this.location,
this.createdAt,
this.email,
this.events,
this.participants,
this.nameOriginater,
});
MAppointment.fromMap(Map<String, dynamic> data) {
id = data['id'];
title = data['title'];
location = data['location'];
createdAt = data['created_at'];
email = data['email'];
events =
List.from(data['events']).map((item) => Events.fromMap(item)).toList();
participants = List.from(data['participants'])
.map((item) => Participants.fromMap(item))
.toList();
nameOriginater = data['name'];
}
}
Event Model
class Events with ChangeNotifier {
DateTime end;
String name;
DateTime start;
bool timed;
Events(this.end, this.name, this.start, this.timed);
Events.fromMap(Map<dynamic, dynamic> data) {
end = data['end'];
name = data['name'];
start = data['start'];
timed = data['timed'];
}
Map<dynamic, dynamic> toMap() {
return {'end': end, 'name': name, 'start': start, 'timed': timed};
}
}
I later get the MAppointment by the provider as items (List<MAppointment> items).
How can I order the event part by date for items[0].events? The reference for the sort should be items[0].events[0].start

How to convert a String to Object in Flutter?

I have two model classes Employee and AdditionalDetails
class Employee{
AdditionalDetails(this.uuid, this.additional_details);
String uuid;
String additional_details;
}
class AdditionalDetails{
AdditionalDetails(this.start, this.end, this.month);
String start;
String end;
String month;
}
And I have a handler in which I am creating objects of AdditionalDetails and pushing into a list.
List<Employee> list = new List<Employee>;
String add1 = AdditionalDetails("start1", "end1", "dec").toString();
String add2 = AdditionalDetails("start2", "end2", "jan").toString();
list.add(1, add1);
list.add(2, add2);
I am displaying these items in a list and on click of each item , I have to display other details in a dialog box.
I am able to get the uuid by iterating over the list but when doing json.decode(additional_details), it is giving this:
SyntaxError: Unexpected token I in JSON at position 0
How can I get the start, end and month properties from the additionalDetails?
I think this is what you want.
class Employee {
Employee(this.uuid, this.additionalDetails);
String uuid;
String additionalDetails;
}
class AdditionalDetails {
AdditionalDetails(
this.start,
this.end,
this.month,
);
final String start;
final String end;
final String month;
#override
String toString() => '$start $end $month';
}
final list = <Employee>[];
final add1 = AdditionalDetails("start1", "end1", "dec").toString();
final add2 = AdditionalDetails("start2", "end2", "jan").toString();
list.add(Employee('1', add1));
list.add(Employee('2', add2));
More cool way:
class Employee {
Employee({
#required this.uuid,
#required this.additionalDetails,
});
final String uuid;
final AdditionalDetails additionalDetails;
factory Employee.fromJson(Map<String, dynamic> json) => Employee(
uuid: json["uuid"],
additionalDetails: json["additionalDetails"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid,
"additionalDetails": additionalDetails.toJson(),
};
}
class AdditionalDetails {
AdditionalDetails({
#required this.start,
#required this.end,
#required this.month,
});
final String start;
final String end;
final String month;
factory AdditionalDetails.fromJson(Map<String, dynamic> json) =>
AdditionalDetails(
start: json["start"],
end: json["end"],
month: json["month"],
);
Map<String, dynamic> toJson() => {
"start": start,
"end": end,
"month": month,
};
}
final list = <Employee>[];
final add1 = AdditionalDetails(start: "start1", end: "end1", month: "dec");
list.add(Employee(uuid: '1', additionalDetails: add1));
final json = add1.toJson(); // Map<String, dynamic>
final startFromJson = json['start'];
final object = AdditionalDetails.fromJson(json); // AdditionalDetails
final startFromObject = object.start;
if you want to create an object out of string instead of jsondecode you should use toJson and fromJson function:
class AdditionalDetails{
AdditionalDetails(this.start, this.end, this.month);
String start;
String end;
String month;
AdditionalDetails.fromJson(Map<String, dynamic> json){
this.start = json['start'];
this.end = json['end'];
this.month = json['month'];
}
Map<String, dynamic> toJson(){
Map<String, dynamic> data = {};
data['start'] = this.start;
data['end'] = this.end;
data['month'] = this.month;
return data;
}
}
List<Employee> list = new List<Employee>;
String add1 = AdditionalDetails("start1", "end1", "dec").toJson();
String add2 = AdditionalDetails("start2", "end2", "jan").toJson();
list.add(1, add1);
list.add(2, add2);
final object = AdditionalDetails.fromJson(add1);