I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!
static List<Widget> getPlates(String file) {
List<Widget> listWidgets = [];
loadAsset('assets/$file.csv').then((dynamic output) {
List<String> list = output.split('\n');
for (int i = 1; i < list.length - 1; i++) {
List<String> sublist = list[i].split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
}
});
return listWidgets;
}
static Future<String> loadAsset(String path) async {
return await rootBundle.loadString(path);
}
Are you talking something like this, or even more indepth?
output.split('\n').forEach((String entry) {
List<String> sublist = entry.split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
})
import 'dart:convert';
static final reg = RegExp(r'assets/\w+\.csv'); //check for all files within assets, not including subfolders
static List<Widget> getPlater() async{
List<Widget> listWidgets = [];
var myAssets = await rootBundle.loadString('AssetManifest.json'); //file generated by flutter which you can read up through the default bundle
Map<String, dynamic> map = json.decode(myAssets);
map.removeWhere((key, value) => !key.contains(reg)); //remove all keys that aren't csv files
for(String path in map.keys){
var output = await rootBundle.loadString(path);
List<String> list = output.split('\n');
for (int i = 1; i < list.length - 1; i++) {
List<String> sublist = list[i].split(';');
listWidgets.add(CardPlate(
name: sublist[0],
ingredients: sublist[1],
price: sublist[2],
));
}
}
return listWidgets;
}
Related
I have a list that I extract it from a txt file then I splitted this list into sublists. now I want to return just 240 items of this list.
this is my code:
static Future<List> localPath() async {
File textAsset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
final text = await textAsset.readAsString();
final bytes =
text.split(',').map((s) => s.trim()).map((s) => int.parse(s)).toList();
int chunkSize = 20;
List<int> padTo(List<int> input, int count) {
return [...input, ...List.filled(count - input.length, 255)];
}
List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
final items = bytes.slices(chunkSize).map(padToChunksize).toList();
return items;
}
```
I want something like:
```
for(int i=0; i<240; i+=chunksize){
return items
}
```
thanks in advance for your help
List.take(count) can be used for this:
return items.take(240).toList();
Hello all at first I want to mention that I've tried a lot of solutions here but it didn't work for me.
I bring the list from the database through the following code:
var listCat = [];
Future getdata() async {
apiURL = '***************.php';
var response = await http.post(Uri.parse(apiURL));
var responsebody = jsonDecode(response.body);
if (responsebody.length >0){
for (int i = 0; i < responsebody.length; i++) {
listCat.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
}
return responsebody;
}else{
}
}
As is obvious in the code above I am trying to get the name and image and this is not a problem right now I want to store this listCat in SharedPreferences until I recall it from all pages of the app
I have the following class to save SharedPreferences:
class APIPreferences {
static SharedPreferences ? _preferences;
static const _keyMuinCat = 'MuinCat';
static Future init() async => _preferences = await SharedPreferences.getInstance();
static Future setMuinCat(String MuinCat) async => await _preferences!.setString(_keyMuinCat, MuinCat);
static String? getMuinCat() => _preferences!.getString(_keyMuinCat);
}
Then I save what I need to save by the following line:
APIPreferences.setMuinCat(listCat.toString());
Then I can bring pre-stored data from any location where I need it through the following code:
CatList = APIPreferences.getMuinCat() ?? '';
I tried to do the following thing now to save the list in the first code above:
var listCat = [];
Future getdata() async {
apiURL = '***************.php';
var response = await http.post(Uri.parse(apiURL));
var responsebody = jsonDecode(response.body);
if (responsebody.length >0){
for (int i = 0; i < responsebody.length; i++) {
listCat.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
APIPreferences.setMuinCat(listCat.toString());
}
return responsebody;
}else{
}
}
But it didn't work. I don't really know how to deal with it.
How can I save it and then bring it to use with ListView.
instead of:
_preferences!.setString(_keyMuinCat, "some string");
use:
_preferences!.setStringList(_keyMuinCat, ["some", "strings", "in", "list"]);
So in your code, the setMuinCat method needs to be:
static Future setMuinCat(List<String> muinCat) async => await _preferences!.setStringList(_keyMuinCat, muinCat);
and then you call it like this:
APIPreferences.setMuinCat((listCat as List).map((v) => v.toString()).toList());
To save the list in shared preferences you need to pass as jsonEncode(yourList data) and when you will fecth the shared list you will again jsonDecode(your list)
await prefs.setString('YOUR KEY', json.encode(YOURMAP()));
I am using flutter desktop development. Use the group button filter to read data from the database and render it to GridView.builder().
At present, I can't realize the filtering function when I read the data sheet from the database[enter image description here][1]
I am using getx
final selected = 'table_operation'.obs;
final items = ['table_operation', 'merge_table', 'turn_table'];
final SqliteHelper _sqliteHelper = SqliteHelper();
final areas = [].obs;
final selectedAreaType = 0.obs;
final tables = [].obs;
// final filterTables = [].obs;
var areaModel;
final areaId = 0.obs;
void setSelected(value) {
selected.value = value;
}
void setSelectArea(int value) {
selectedAreaType.value = value;
areaModel = areas[selectedAreaType.value];
areaId.value = areaModel.id;
}
#override
onInit() {
getAreaList();
getTableList();
super.onInit();
}
Future<List<AreaModel>> getAreaList() async {
List<Map<String, dynamic>> results = await _sqliteHelper.queryObject('area');
List<AreaModel> areaList = [];
for (var r in results) {
if (r.isNotEmpty) {
areaList.add(AreaModel.fromMap(r));
}
}
areas.value = areaList.map((e) => e).toList();
return areaList;
}
Future<List<TableModel>> getTableList() async {
List<Map<String, dynamic>> results = await _sqliteHelper.queryObject('tables');
List<TableModel> tableList = [];
for (var t in results) {
tableList.add(TableModel.fromMap(t));
}
tables.value = tableList.map((e) => e).toList();
return tableList;
}
[1]: https://i.stack.imgur.com/fOGwg.png
how to convert excel sheet into json in flutter.
I have a excel sheet of students names and classes and i want to convert it to json to make it easy to run the app or another way to upload date to firestore.
Future<String> excelToJson() async {
var file = await FilePicker.getFilePath(
type: FileType.custom, allowedExtensions: ['xlsx', 'csv', 'xls']);
var bytes = File(file).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = new List<dynamic>();
List<Map<String, dynamic>> json = new List<Map<String, dynamic>>();
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
if (i == 0) {
keys = row;
i++;
} else {
Map<String, dynamic> temp = Map<String, dynamic>();
int j = 0;
String tk = '';
for (var key in keys) {
tk = "\u201C" + key + "\u201D";
temp[tk] = (row[j].runtimeType==String)?"\u201C" + row[j].toString() + "\u201D":row[j];
j++;
}
json.add(temp);
}
}
}
print(json.length);
String fullJson = json.toString().substring(1, json.toString().length - 1);
return fullJson;}
I want to learn how to use this script in my application or another way is more easy and simple
Thanks
Use this methods:
Future<void> excelToJson(String fileName, String fileDirectory,GlobalKey<ScaffoldState> scaffoldKey) async {
ByteData data = await rootBundle.load(fileDirectory);
var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = new List<dynamic>();
List<Map<String, dynamic>> json = new List<Map<String, dynamic>>();
for (var table in excel.tables.keys) {
for (var row in excel.tables[table].rows) {
if (i == 0) {
keys = row;
i++;
} else {
Map<String, dynamic> temp = Map<String, dynamic>();
int j = 0;
String tk = '';
for (var key in keys) {
tk = '"' + key + '"';
temp[tk] = (row[j].runtimeType == String)
? '"' + row[j].toString() + '"'
: row[j];
j++;
}
json.add(temp);
}
}
}
print(json.length);
String fullJson = json.toString().substring(1, json
.toString()
.length - 1);
fullJson = '{ "DATA" : [$fullJson]}';
final directory = await getExternalStorageDirectory();
File file = await File('${directory.path}/$fileName.json').create();
await file.writeAsString(fullJson).then((value) =>
scaffoldKey.currentState
.showSnackBar(SnackBar(content: Text("Completed")))
);
print(file.exists().toString());
}
Future<void> jsonToExcel(String fileName, String fileDirectory,GlobalKey<ScaffoldState> scaffoldKey) async{
String jsonString = await rootBundle.loadString(fileDirectory);
List<dynamic> jsonResult = jsonDecode(jsonString)["DATA"];
var excel = Excel.createExcel();
Sheet sheetObject = excel['Sheet1'];
Map<String,dynamic> result = jsonResult[0];
sheetObject.appendRow(result.keys.toList());
for(int i =0;i<jsonResult.length;i++){
Map<String,dynamic> result = jsonResult[i];
sheetObject.appendRow(result.values.toList());
}
final directory = await getExternalStorageDirectory();
excel.encode().then((onValue) {
File(("${directory.path}/$fileName.xlsx"))
..createSync(recursive: true)
..writeAsBytesSync(onValue);
scaffoldKey.currentState
.showSnackBar(SnackBar(content: Text("Completed")));
});
print(sheetObject);
}
Updated your code just a bit....
Future<String> excelToJson() async {
FilePickerResult result =await FilePicker.platform.pickFiles(type:FileType.custom,allowedExtensions: ['xls','xlsx','csv']);
if (result != null) {
File excelFile = File(result.files.single.path);}
var bytes = File(excelFilePath).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
int i = 0;
List<dynamic> keys = [];
var jsonMap = [];
for (var table in excel.tables.keys) {
dev.log(table.toString());
for (var row in excel.tables[table].rows) {
dev.log(row.toString());
if (i == 0) {
keys = row;
i++;
} else {
var temp = {};
int j = 0;
String tk = '';
for (var key in keys) {
tk = '\"${key.toString()}\"';
temp[tk] = (row[j].runtimeType == String)
? '\"${row[j].toString()}\"'
: row[j];
j++;
}
jsonMap.add(temp);
}
}
}
dev.log(
jsonMap.length.toString(),
name: 'excel to json',
);
dev.log(jsonMap.toString(), name: 'excel to json');
String fullJson =
jsonMap.toString().substring(1, jsonMap.toString().length - 1);
dev.log(
fullJson.toString(),
name: 'excel to json',
);
return fullJson;
}
I am using this package to retrieve device's contacts. The lib retrieve 427 contacts and I want to loop the whole list so that I can create another list and send it to the back-end. The problem is looping does not work this the function return before looping is completed.
Here the function I use:
Future<QueryResult> uploadContacts() async {
final List<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
List<ContactInput> contactsListInput;
print('contactsListInput length: ${rawContacts.length}');
rawContacts.forEach((contact) {
print('contact: $contact'); //PRINTED JUST ONCE
//Contact can have more than 1 number. We need them all
contact.phones.forEach((phone) {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
print('contactsListInput length: ${contactsListInput.length}'); //NEVER PRINT ANYTHING
final ContactsListInput input =
ContactsListInput(contacts: contactsListInput);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
I have also tried using for loop and the same thing happened.
for (int i = 0; i < rawContacts.length; i++) {
final contact = rawContacts[i];
final contactInput =
ContactInput(name: contact.displayName, phone: contact.phones.first.value);
contactsListInput.add(contactInput);
}
print('contactsListInput length: ${contactsListInput.length}'); //NEVER CALLED
And I also tried Future.forEach
await Future.forEach(rawContacts, (contact) async {
print('contact: $contact');
//Since contact can have more than one number we loop them too.
await Future.forEach(contact.phones, (phone) async {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
How to fix this? Any help will be much appreciated.
I have fixed it as
Future<QueryResult> uploadContacts() async {
final Iterable<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false));
final Iterable<ContactInput> contacts = rawContacts.expand((contact) => contact.phones.map(
(phone) =>
ContactInput(name: contact.displayName, phone: phone.value)));
final input = ContactsListInput(contacts: contacts);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
Credit goes to #pskink and #loganrussell48
You should use it as a dynamic type object. Try something like this:
(event.snapshot.value as dynamic).forEach()
Try and see if it works.