How to Store list in String in sqflite flutter? - flutter

I am using sqflite package for local Storage I need to store list of json in String, then Particular String again I need reconvert into Json list.

json
{
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
]
}
Convert
import 'dart:convert';
final data = {
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
],
};
final String dataAsJson = json.encode(data);
Inserting Data after opening database
import 'package:sqflite/sqflite.dart';
await db.insert(
'images', # the name of the table
{'data': dataAsJson}, # `data` is the column's name
);
Getting Data
final List<Map> maps = await db.query('images', columns: ['id', 'data']);
final dataFromJsonToMap = json.decode(maps[0]);

Related

Dart - Convert Map of objects fetched via HTTP REST-API

For my Calendar i get the following data as JSON from the Backend (*JAVA-Type = Map<LocalDate, List<Event>>):
{
"2022-05-28": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
}
],
"2022-05-27": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
},
{
"id": 1,
"title": "Testevent",
"fromDate": "2022-05-27T11:21:04.573754",
"toDate": "2022-05-27T12:21:04.573754",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "normal"
}
],
}
My Event Class looks like:
Class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
}
Now i need the same structure i had in the Backend (Map<DateTime, <List<Event>>) for my Calendar widget and i have no real clue on how to do it. I know how to convert json data into an object if i get a list of an object, but how can i store the date as key of the resulting map?
My code by now:
Future<Map<DateTime, List<Event>>> getEvents(DateTime _fromDate, DateTime
_endDate) async {
String _from = _fromDate.toString().split('.').first;
String _end = _endDate.toString().split('.').first;
final response = await get('${_url}calendar/events/$_from/$_end',
headers: {HttpHeaders.authorizationHeader: 'Bearer $_bearer'});
if (response.status.hasError) {
return Future.error('${response.statusText}');
} else {
final parsed = jsonDecode(response.body);
return parsed;
}
}
You need to do something like that:
var json = {...}; // <-- json obj
// method to parse data to map with list Event
dynamic fromJson(Map<String, dynamic> json){
var map = new Map();
json.keys.forEach((key){
// key is the date
map[key] = json[key].map((e) => Event.fromJson(e)).toList(); // <- need to create a method fromJson in your Event class
});
return map;
}
(...)
class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
fromJson(Map<String, dynamic> json) => Event(...); // <- parse json to Event class
}

Use Json data file on Flutter unit test

I would like to do the unit test for model by Flutter.
Then I want to use test json data.
But I got the error message.
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast
I want to know how to solve this issue.
Here is the test codes.
void main() {
group('Gift Test', () {
test('Gift model test', () {
final file = File('json/gift_test.json').readAsStringSync();
final gifts = Gift.fromJson(jsonDecode(file) as Map<String, dynamic>);
expect(gifts.id, 999);
});
});
}
Here is the model
#freezed
abstract class Gift with _$Gift {
#Implements(BaseModel)
const factory Gift({
int id,
String name,
int amount,
Image image,
}) = _Gift;
factory Gift.fromJson(Map<String, dynamic> json) => _$GiftFromJson(json);
}
And this is the test data.
[
{
"id": 999,
"name": "testest",
"amount": 30000,
"image": {
"id": 9999,
"image": {
"url": "https://text.jpg",
},
},
}
]
Your json file is a list, not an object, either you change your json file in
{
"id": 999,
"name": "testest",
"amount": 30000,
"image": {
"id": 9999,
"image": {
"url": "https://text.jpg",
},
},
}
Or you will need to update your code to take the first element of the list:
final file = File('json/gift_test.json').readAsStringSync();
final gifts = Gift.fromJson((jsonDecode(file) as List).first as Map<String, dynamic>);

How to pass a list of json to body of http Post request in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
submitQuestions() async {
var headers = {
'Content-Type': 'application/json',
'x-auth-token': '123edrfe33ewed'
};
var request = http.Request('POST', Uri.parse('url'));
request.body = json.encode({
"school_id": "123",
"teacher_id": "123",
"observer_id": "123",
"subject_id": "123",
"subject_name": "abc",
"class_id": "123",
"batch_id": "123",
"topic": "topic",
"academic_year": "2019-2020",
"remarks_data": [
{
"_id": "123",
"heading": "heading",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 4
},
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 1
}
]
},
{
"_id": "123",
"heading": "abc",
"Indicators": [
{
"name": "abc",
"_id": "123",
"remark": "abc",
"point": 3
}
]
}
]
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
}
This json will change dynamically when the number of questions increase. I cannot place this json file in the body like this. How to Do this one.
Wrap each list of json with jsonEncode
like:
"remarks_data": jsonEncode(..)
and do not forget to import.
import 'dart:convert';
The request body try to use Map data type. You can create a model class to deal with it.
Example
class School {
String school_id;
String teacher_id;
String observer_id;
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['school_id'] = this.school_id;
data['teacher_id'] = this.teacher_id;
data['observer_id'] = this.observer_id;
...
return data;
}
}
/// Make sure your _school got data
School _school;
request.body = _school.toJson();

How do you parse JSON that is inside an array

I am new to flutter development and is experimenting with how to use the flutter HTTP package 0.12.0+2.
If the response looks like this...
{
"coord": {
"lon": -76.8403,
"lat": 38.9649
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 93.47,
"feels_like": 99.34,
"temp_min": 88.84,
"temp_max": 97.74,
"pressure": 1017,
"humidity": 46
},
"visibility": 10000,
"wind": {
"speed": 1.99,
"deg": 304,
"gust": 1.99
},
"clouds": {
"all": 1
},
"dt": 1626462013,
"sys": {
"type": 2,
"id": 2030617,
"country": "US",
"sunrise": 1626429293,
"sunset": 1626481895
},
"timezone": -14400,
"id": 4369076,
"name": "Seabrook",
"cod": 200
}
Here is the code I have. Instead of printing all the data, how do I print only temp inside main
void getData() async {
Response response = await get('https://api.openweathermap.org/data/2.5/onecall?lat=38.964882&lon=-76.840271&exclude={part}&appid=b29e187fed23cf37dc160e6c115a270d');
// print(response.body);
Map data = jsonDecode(response.body);
print(data);
}
You can use:
void getData() async {
Response response = await get('https://api.openweathermap.org/data/2.5/onecall?lat=38.964882&lon=-76.840271&exclude={part}&appid=b29e187fed23cf37dc160e6c115a270d');
// print(response.body);
Map data = jsonDecode(response.body);
print(data['main']); //Will return [temp], [feels_like], [temp_min], etc..
print(data['main']['temp']); //Will return [93.47]
}
You can access the values of each fields by using the operator [$field] on the decoded json. Something like this:
void getData() async {
Response response = await get('https://api.openweathermap.org/data/2.5/onecall?lat=38.964882&lon=-76.840271&exclude=.{part}&appid=b29e187fed23cf37dc160e6c115a270d');
// print(response.body);
Map data = jsonDecode(response.body);
print(data['main']); // prints out { temp: 93.47, ...., humidity: 46 }
// what you want..
final mainTemp = data['main']['temp'];
print(mainTemp); // prints out 93.47.
print(data);
}
So, that's how you access the fields of of the decoded json-string response.
If you plan to use these received values throughout your app, consider changing the received response into an Interface which will provide you with more flexibility and also makes your code look cleaner.
Create Model Class here you can convert json to dart
https://javiercbk.github.io/json_to_dart/
Future<YourmodelName>getData() async {
YourmodelName data
Response response = await get('https://api.openweathermap.org/data/2.5/onecall?
lat=38.964882&lon=-76.840271&exclude=
{part}&appid=b29e187fed23cf37dc160e6c115a270d');
if (response.statusCode == 200) {
data = YourmodelName.fromJson(response.data);;
print(data.main.temp);}
return data;
}

What is the right way to fetch data from network with n:m relation and store both as a model class and reference on each side in flutter?

I spent days to think&googled about how to achieve this, but still can't get any idea how it actually works...
I would appreciate if someone could give me some advise or point me to the right direction.
So in my case, I will fetch a json list from an APIs, and I just wanna store the Shop class into a list which will build in a listView.
Here's my code sample.
Widget buildShopList() {
return ListView.builder(
itemCount: shopList.length,
padding: const EdgeInsets.only(top: 8, bottom: 110),
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
final int count = shopList.length > 10 ? 10 : shopList.length;
return ShopListView(
callback: () {},
shop: shopList[index],
);
},
);
}
class ShopListView extends StatelessWidget {
const ShopListView({Key key, this.shop}: super(key: key);
final Shop shop;
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(shop.type.name),
Text(shop.name),
]
);
}
}
Shop model class
class Shop {
String name;
String website;
String email;
ShopType type;
Shop({this.name, this.website, this.email, this.type});
factory Shop.fromJson(Map<String, dynamic> json) => Shop(
name: json["name"],
type: json["shop_types"],
// can't figure out how to pass the shop type model class into here
website: json["website"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"name": name,
"shop_types": type,
"website": website,
"email": email
};
}
ShopType model class
class ShopType {
int id;
String name;
String description;
ShopType({this.id, this.name, this.description});
factory ShopType.fromJson(Map<String, dynamic> json) => ShopType(
id: json["id"],
name: json["name"],
description: json["description"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
};
}
Here's the json will response from APIs
{
"success": true,
"data": {
"shops": [
{
"id": 1,
"name": "shop name a",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
"pivot": {
"shop_id": 1,
"shop_type_id": 1
}
}
]
},
{
"id": 2,
"name": "shop name b",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 2,
"name": "Store",
"description": "Store",
"pivot": {
"shop_id": 2,
"shop_type_id": 2
}
}
]
},
{
"id": 3,
"name": "shop name c",
"website": "http://www.test.com/",
"email": "test#test.com",
"description": "this is a dummy data",
"shop_types": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
"pivot": {
"shop_id": 3,
"shop_type_id": 1
}
},
{
"id": 2,
"name": "Type B",
"description": "Type B",
"pivot": {
"shop_id": 3,
"shop_type_id": 2
}
}
]
}
],
"shopTypes": [
{
"id": 1,
"name": "Type A",
"description": "Type A",
},
{
"id": 2,
"name": "Type B",
"description": "Type B",
}
]
}
}
Fetch data From network with Dio
fetchShopsAndSaveLocal() async{
var dio = Dio();
dio.options.connectTimeout = 4500 * 10; //45s
dio.options.receiveTimeout = 4500 * 10;
try {
var param = {
"useremail": "dpk.7#gmail.com"
, "password": "123456"};
var response = await dio.post(
"https://api.test/getstores", data: FormData.fromMap(param));
var json = jsonDecode(response.data);
ModelStore store = ModelStore.fromJson(json);
List<Shops> shops = store.shops;
for (var shop in shops) {
saveEverySingleShopInDatabase(shop);
}
} catch (e) {}
}
After that use SQFlite
To Save shops data in Database, after saving data in the local database, fetch data to listview every time from the database.