json to sqflite create table query Flutter - flutter

Is there an automatic way to generate sqflite create table queries according to json data?
I m building Erp apps.So, i have to deal with 40-50 tables each time and
i think there should be an automatic way to do it like json to dart.
{
"sto_code": "120.001",
"sto_name": "NORMAL STOK",
"sto_amount": 1
}

No package that I know of does that yet. But you could use this code snippet to generate a CREATE TABLE statement with an example json file.
String getType(Type type){
if(type is int){
return 'INTEGER';
}else if(type is String){
return 'TEXT';
}else if(type is double){
return 'REAL';
}else{
return 'TEXT';
}
}
String createColumns(Map<dynamic, dynamic> map){
String columns = '';
map.forEach((key, value){
columns += '$key ${getType(value.runtimeType)}, ';
});
return columns.endsWith(', ') ? columns.substring(0,columns.length - 2) : columns;
}
String createTable(String tableName, Map<dynamic, dynamic> map){
String columns = createColumns(map);
String table = 'CREATE TABLE $tableName ($columns)';
return table;
}

Related

How do I print my inserted values in my console? (Flutter | sqflite)

I am currently successfully able to insert values into the system, however, I want to be able to display the inserted values in my console.
How do I print the inserted values in my console? I tried doing so and I was only able to get the "id" of the inserted value. I'm not sure how to print the rest of the values in the table.
Here's my insert code:
// Insert Operation: Insert a Note object to database
Future<int> insertNote(Note note) async {
//getting db reference
Database db = await database;
//running the insert command
//our data from note is converted to map object
var result = await db.insert(noteTable, note.toMap());
if (kDebugMode) {
print('Note data inserted successfully: $result');
}
return result;
}
Here's the code I used to convert the Note object into a Map object
// Convert a Note object into a Map object
Map<String, dynamic> toMap() {
var map = <String,dynamic>{};
if (id != null) {
map['id'] = _id;
}
map['title'] = _title;
map['description'] = _description;
map['priority'] = _priority;
map['color'] = _color;
map['date'] = _date;
return map;
}
This is the result on my console:
When you insert row in database you will only get row id in return.
So if you want to print recent data then you have to make a query to your database with id or you can also print all the data available.
For table
db.query("table_name);
or
db.rawQuery('SELECT * FROM "table"');
For specific id
db.query("table_name",where: '$rowId = ?', whereArgs: [id]);
or
db.rawQuery('SELECT * FROM "table" WHERE $rowId = $id');
For more info check : https://pub.dev/packages/sqflite

How to update Model with the correct value type

I have this code that fetch data from internet:
Future fetchCfo(String barCode, String url) async {
final response = await http.get(Uri.parse(url + barCode));
if (response.statusCode == 200) {
Map<String, dynamic> responseBody = json.decode(utf8.decode(response.bodyBytes));
responseBody.forEach((key, value) {
if (value == null) {
responseBody.update(key, (value) => "");
}
});
return CfoModel.fromJson(responseBody);
} else {
return null;
}
}
And I need to replace the null values ​​according to their type, for example if a field that was supposed to be an integer returns a null I need to replace it with 0, if a field that was supposed to be a list returns a null I need to replace it with a list empty []; and I don't know how to do this, my code replaces Strings but if a null appears in an int field, the code breaks.
For example, my model:
String? interfaceStatus;
bool? trasnP;
int? id;
String? name;
String? date;
bool? requiredStatus;
int? numberOf;
int? numberRegion;
List? parameters;
In case numberRegion returns a null, I need to replace with 0;
In case Transp returns a null, I need to replace with false;
in case name returns a null, I need to replace with empty String "";
Response I'm getting:
{
"interfaceStatus":"ok",
"trasnP":false,
"id":null,
"name":null,
"date":null,
"requiredStatus":true,
"numberOf":23,
"numberRegion":27,
"parameters":null
}
What I want to return:
{
"interfaceStatus":"ok",
"trasnP":false,
"id":0,
"name":"",
"date":"",
"requiredStatus":true,
"numberOf":23,
"numberRegion":27,
"Parameters":[
]
}
Anyone has a solution for this ?
I would recommend not updating any values in the responseBody just leave them as null but in the fromJson function you can give default values with the ?? operator such as:
fromJson(Map response) {
return CfoModel(
id: response[id] ?? 0,
array: response[array_element] ?? [],
);
}

Mapping CSV data in flutter

Auto-complete search list
How to parse csv data instead of json data as mentioned in this article. I am new to csv and I have trouble mappping csv data to a model list. I need to pass the csv list to autocomplete field in another package plz help me in mapping it to the model.
class Players {
String keyword;
int id;
String autocompleteterm;
String country;
Players({
this.keyword,
this.id,
this.autocompleteterm,
this.country
});
factory Players.fromJson(Map<String, dynamic> parsedJson) {
return Players(
keyword: parsedJson['keyword'] as String,
id: parsedJson['id'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
country: parsedJson['country'] as String
);
}
}
class PlayersViewModel {
static List<Players> players;
static Future loadPlayers() async {
try {
players = new List<Players>();
String jsonString = await rootBundle.loadString('assets/players.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['players'] as List;
for (int i = 0; i < categoryJson.length; i++) {
players.add(new Players.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}

Excel flutter read data by columns

Is it possible to fetch the data existing in a file.xlsx using Excel dependency by columns?
I mean for each column that exist in the sheet it should be stored in a list for example.
I have only found how to fetch data by rows using:
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// code
}
}
Is there any way to do this by columns?
Thank you.
I think this code from example is you need:
/// Iterating and changing values to desired type
for (int row = 0; row < sheet.maxRows; row++) {
sheet.row(row).forEach((cell) {
var val = cell.value; // Value stored in the particular cell
});
}
Found a temporary solution, downside is that you need to get column heading(s) for getting their values, below is the code if it helps you out:
Future<List<ExcelSheetData>> getExcelFile(BuildContext context, String name, String email) async {
FilePickerResult pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
allowMultiple: false,
);
List<ExcelSheetData> excelList = [];
int nameIndex;
int emailIndex;
if (pickedFile != null) {
setAddMembersLoadingTrue();
var file = pickedFile.paths.single;
var bytes = await File(file).readAsBytes();
Excel excel = await compute(parseExcelFile, bytes);
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
// name variable is for Name of Column Heading for Name
if (row?.any((element) => element?.value?.toString() == name) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == name);
nameIndex = data.colIndex;
}
// email variable is for Name of Column Heading for Email
if (row?.any((element) => element?.value?.toString() == email) ?? false) {
Data data = row?.firstWhere((element) => element?.value?.toString()?.toLowerCase() == email);
emailIndex = data.colIndex;
}
if (nameIndex != null && emailIndex != null) {
if (row[nameIndex]?.value.toString().toLowerCase() != name.toLowerCase() && row[emailIndex]?.value.toString().toLowerCase() != email.toLowerCase())
excelList.add(
ExcelSheetData(
name: row[nameIndex]?.value.toString(),
email: row[emailIndex]?.value.toString(),
),
);
}
}
}
setAddMembersLoadingFalse();
return excelList;
}
return null;
}
refer to this question if you need more clarification

How to Adding New Data into JSON Dart?

I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}