How to define SharedPreferences from an Object? - flutter

I'm using shared_preferences.dart package. When the user login in the App, I load some preferences from an object of Settings named Configuracion that looks like attached.
The way I'm loading _prefs is as follows...
final _prefs = new PreferenciasUsuario();
ConfiguracionModel _configuracion = new ConfiguracionModel();
_configuracion = await configuracionBloc.cargarConfiguracion(_prefs.idEmpresa);
_prefs.idioma = _configuracion.idioma;
_prefs.medidaDistancia = _configuracion.medidaDistancia;
_prefs.medidaOxigeno = _configuracion.medidaOxigeno;
_prefs.medidaPeso = _configuracion.medidaPeso;
_prefs.medidaPesoUnidad = _configuracion.medidaPesoUnidad;
_prefs.medidaTemp = _configuracion.medidaTemp;
//......a large list of more and more ....
Is there a way to reduce the large amount of code?
Something like _prefs... = _configuracion...

Related

How can i convert 'X' to '*' and them compute it in dart

i am building a calculator app although its working fine but i just want to make it look like this before its is been turn into mathematical expression:
how do i achieve something like this:
'5X4' = 20
instead of using the asterisk sign '5*4' = 20
like i want to be able to replace the string 'X' in background before it's been computed
i tried this code below:
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final result = computed;
if i run the
print(result)
but if i try
print(int.parse(result));
the console print out
Uncaught Error: FormatException: 5*4
how do i fix this?
You can use expressions package. Here is an example:
String data = "12x2÷3-2+4";
data = data.replaceAll("x", "*");
data = data.replaceAll("÷", "/");
Expression expression = Expression.parse(data);
const evaluator = ExpressionEvaluator();
var r = evaluator.eval(expression, {});
print(r.toString()); // 10.0
You should try this approach.
final multiply = '5X4';
final computed = multiply.replaceAll('X','*');
final List<String> variable1 = computed.split('*');
final result = int.parse(variable1.first) * int.parse(variable1.last);
final lastResult = '$computed = $result';
print(lastResult);
Dartpad

Flutter How to get all files from assets folder in one List

I have a bunch of xml files in assets folder, I add path to pubspec.yaml and path looks like this 'assets/data/somename.xml' I need to get data from them and this is the way how i got it now
List filePathList = ['assets/data/widow.xml','assets/data/door.xml'];
for(int i = 0;i<filePathList.length;i++){
var xmlFile = XmlDocument.parse(await rootBundle.loadString(filePathList[i]));
checkListtemplateXmlList.add(xmlFile);
}
How you can see i use realy bad way to take data from files,
there will be many more xml files in the future so i need some solution to this problem to not add path in filePathList for every file in assets folder.
Also i made a loadData function that load all files like i want, but my json files are in directory that i got with using getApplicationDocumentDirectory class. There is a code
static Future<void> loadData() async {
final dir = await getApplicationDocumentsDirectory();
List<FileSystemEntity> files = await dir.list().toList();
for (int i = 0; i < files.length; i++) {
String filepath = files[i].path;
File newFile = File(filepath);
String name = p.basenameWithoutExtension(newFile.path);
String myExtension = p.extension(filepath);
if(myExtension != '.json'){
} else{
checkLists.add(CheckList(name));
}
}
for(int i = 0;i< checkLists.length;i++){
await checkLists[i].readFile();
}
}
how i can do something like this in my getXmlData function
Inside the pubspec define only the folder:
assets:
- assets/data/
This will "load" all files inside the data folder.
And using this code:
// This will give a list of all files inside the `assets`.
var assets = await rootBundle.loadString('AssetManifest.json');
And use a filter to get all xml files.
Map json = json.decode(assets);
List get = json.keys.where((element) => element.endsWith(".xml")).toList();

How to get the overall size of the database? - Flutter

I'm having a couple of tables in a particular database and so i was hoping to get the size of the database when the data is dumped into the particular tables.
This is how i tried
var db = await openDatabase('dummy.db');
int count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM dummyTable1'));
I know this approach is wrong since I'm getting only the number of rows in the particular table but how to get the size of the particular table?
Something like this will tell you the size of your db
final databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'dummy.db');
final file = File(path);
Now you can get the file size with
final size = file.lengthSync();
or
final size = await file.length();
or alternatively if flutter db support it, you can have a look here:
https://www.sqlite.org/pragma.html#pragma_page_count

How to allow users to upload files with Google Form without login?

Where can I find code and instruction on how to allow users to upload files with Google Form without login?
I searched all over here and couldn't find any information.
https://developers.google.com/apps-script/reference
Thanks in advance.
The user will be uploading the files to your drive. So, google needs to verify the user. If there is no verification, someone can fill your drive in no time.
It is for your safety to know who has uploaded, so, login is must.
There's a workaround, I'm in a hurry to write the code now, but if you're interested let me know and I'll edit later.
Basically, you set up a web app with apps script, then you setup a custom HTML form, you'll have to manually collect the file, convert is to base64 then json, then when you catch it in apps script you reverse the process and save it wherever you want in your drive.
Since the user will be executing the script as you, there's no verification required
/*
These functions basically go through a file array and reads the files first as binary string (in second function), then converts the files to base64 string (func 1) before stringifying the files (after putting their base64 content into an object with other metadata attached; mime, name e.t.c);
You pass this stringified object into the body part of fetch(request,{body:"stringified object goes here"})
see next code block for how to read in apps script and save the files to google drive
N.B. The body data will be available under doPost(e){e.postData.contents}
*/
async function bundleFilesForUpload(){
let filesDataObj = [];
let copy = {fileInfo:{"ogname":"","meme":""},fileData:""};
for(let i = 0 ; i < counters.localVar.counters.filesForUploadArr.length ; i++){
let tempObj = JSON.parse(JSON.stringify(copy));
let file = counters.localVar.counters.filesForUploadArr[i];
tempObj.fileInfo.ogname = file.name;
tempObj.fileInfo.meme = file.type;
tempObj.fileData = await readFile(file).then((file)=>{
file = btoa(file);
return file;
}).then((file)=>{
return file;
})
filesDataObj.push(tempObj);
}
return filesDataObj;
}
async function readFile (file){
const toBinaryString = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
let parsedFile = null;
parsedFile = await toBinaryString(file);
return parsedFile;
}
/*From doPost downward, we read the file Array convert the base64 to blob and make a file in google drive using the blob and metadata we have, you may also see some sheet code, I'm using sheet as db for this */
//in buit function doPost in Code.gs
doPost(e){
const myDataObj = JSON.parse(e.postData.contents);
mainFileFunc(myDataObj.params[0].dataObj.images);
//the actual object structure might look different from yours, console log around
}
function mainFileFunc(fileArr) {
let myArrObj = [{"madeit":"toFileF"}];
let copy = JSON.parse(JSON.stringify(myArrObj[0]));
//sheet.getRange("A1").setValue(JSON.stringify(fileArr.length));
for(let i=0 ; i < fileArr.length ; i++){
myArrObj.push(copy);
let blob = doFileStuff(fileArr[i].data,fileArr[i].info[0].mime,fileArr[i].id);
myArrObj[i] = uploadFileOne(blob,fileArr[i].id);
myArrObj[i].mime = fileArr[i].info[0].mime;
myArrObj[i].realName = fileArr[i].name;
// sheet.getRange("A"+(i+1)).setValue(myArrObj[i].name);
// sheet.getRange("B"+(i+1)).setValue(myArrObj[i].url);
// sheet.getRange("C"+(i+1)).setValue(myArrObj[i].mime);
// sheet.getRange("D"+(i+1)).setValue(myArrObj[i].size);
}
return myArrObj;
}
function doFileStuff(filedata,filetype,filename){
var data = Utilities.base64Decode(filedata, Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(data,filetype,filename);
return blob;
}
function uploadFileOne(data,filename) {
let myObj = {}
myObj["name"] = "";
myObj["realName"] = "Story_Picture";
myObj["url"] = "";
myObj["mime"] = "";
myObj["size"] = "";
myObj["thumb"] = "nonety";
var folders = DriveApp.getFoldersByName("LadhaWeb");
while (folders.hasNext()) {
var folder = folders.next();
folder.createFile(data);
}
var files = DriveApp.getFilesByName(filename);
while (files.hasNext()) {
var file = files.next();
myObj.name = file.getName();
myObj.url = file.getUrl();
myObj.mime = file.getMimeType();
myObj.size = file.getSize();
}
return myObj;
}
You can view the full frontend code for this project here and the backend here.
Hope this helps someone.

Flutter, How to get all the image file name from images folder?

I want to load all the image file names in images/pets/ to List<String> animals. How can I do that?
path_provider you can get the directory the temp and appDir directory
final directory = await getApplicationDocumentsDirectory();
String imagesDirectory = directory + "/images/pets/";
After you can use the listSync method to find files of this Directory
final myDir = new Directory(imagesDirectory);
List<FileSystemEntity> _images;
_images = myDir.listSync(recursive: true, followLinks: false);
I hope that I have helped in some way
Flutter generates a file called AssetManifest.json which you can read up through the default bundle the same way you would read a normal text file from the assets.
var manifestContent = DefaultAssetBundle.of(context).loadString('AssetManifest.json');
Read and parse this file and then create a list from all the properties you need with their paths. Just double check to make sure you have the correct path, this can change in the future. It seems to me like a placeholder.
Pseudo-code for reading AssetManifest.json
var manifestContent = DefaultAssetBundle.of(context).loadString('AssetManifest.json');
var manifestMap = json.decode(manifestContent);
var imagePetPaths = manifestMap.keys.where((key) => key.contains('images/pets/'));
// You can either use the keys and fetch the value from the map,
or just use the key value since it's the same as the one in the pubspec.yaml
Continuing from AdsHan's Answer
final dir = await getApplicationDocumentsDirectory();
final imagesDirectory = Directory(dir.path + "/images/pets/");
List<String> images = [];
final _imagesFile = imagesDirectory.listSync(followLinks: false, recursive: true);
_imagesFile.forEach((img) {
String imgString = img.toString().substring(
img.toString().lastIndexOf('/') + 1,
img.toString().length);
images.add(imgString);
});