Save an array to device - arrays

I am trying to save certain data on the device that is running my app. The code for saving the data looks like this:
Future<File> writeContent() async {
final file = await _localFile;
// Write the file
return file. ...;
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print(directory.path);
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/UserData.txt');
}
My problem is that I don't simply want to save a String I want to save a list (array) to the Phone. Is there a way to do so?
There has to come something where you see the ....
Thanks for your answers in advance!

You should use local database like SQLite to handle this problem, you can use this package Link

You can use pref_dessert package to achieve this..
You can create a custom class with what are all the details you want to store..
And everytime you want to store something..create an object for it same that object..
Similarly.. whenever you need the stored details...you can get the object and read details from it.
You can get to know more from an example here.

Related

How to read a list of objects from a file in Dart/Flutter

I am developing a Flutter App, and I wish to save a list of objects (Contacts) to the app directory.
As suggested in the Cookbook, I use the path_provider package and the File class of Dart.
Getting to write the objects was easy (I think - I didn't get any error). Here is the code I used for writing the list:
Future<void> writeContact(List<Contact> contacts) async {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/contacts.txt');
// Write the file
IOSink sink = file.openWrite(mode: FileMode.write);
sink.write(contacts);
sink.close();
}
The question is - how to I read this file and populate the List of Contacts?
Thanks, Gal.

Share file from url

I'm working on a project that needs to share a pdf file and that file is stored in the firebase storage.
I've researched different sharing libs and all seems to share files from the internal storage or share the url directly as text (this could be an option, but product team doesn't want it).
So my question is, is there a way different than manually download the pdf, save it in the internal storage and then share it as any file?
This seems to me like a not so strange use case, so someone may have a better solution :)
You can use this package to share files https://pub.dev/packages/esys_flutter_share
Future<void> _shareMixed() async {
try {
final ByteData bytes1 = await rootBundle.load('assets/image1.png');
final ByteData bytes2 = await rootBundle.load('assets/image2.png');
final ByteData bytes3 = await rootBundle.load('assets/addresses.csv');
await Share.files(
'esys images',
{
'esys.png': bytes1.buffer.asUint8List(),
'bluedan.png': bytes2.buffer.asUint8List(),
'addresses.csv': bytes3.buffer.asUint8List(),
},
'*/*',
text: 'My optional text.');
} catch (e) {
print('error: $e');
}
}
full example can be found in following link code

How to upload a local json file using Blazor

I am trying to select a local json file and load it in my blazor client component.
<input type="file" onchange="LoadFile" accept="application/json;.json" class="btn btn-primary" />
protected async Task LoadFile(UIChangeEventArgs args)
{
string data = args.Value as string;
}
P,S I do not understand , do i need to keep track both the name of the file and the content when retrieving it ?
I guess you're trying to read the contents of a JSON file on the client (Blazor), right? Why not on the server !?
Anyhow, args.Value can only furnish you with the name of the file. In order to read the contents of the file, you can use the FileReader API (See here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader). That means that you should use JSIntrop to communicate with the FileReader API. But before you start, I'd suggest you try to find out if this API have been implemented by the community (something like the localStorage, etc.). You may also need to deserialize the read contents into something meaningful such as a C# object.
Hope this helps...
There is a tool that can help, but it currently doesn't support the 3.0 preview. https://github.com/jburman/W8lessLabs.Blazor.LocalFiles
(no affiliation with the developer)
The input control will give you the location of the file as a full path along with the name of the file. Then you still have to retrieve the file and download it to the server.
Late response but with 3.1 there is an additional AspNetCore.Components module you can download via NuGet to get access to HttpClient extensions. These make it simple:
// fetch mock data for now
var results = await _http.GetJsonAsync<WellDetail[]>("sample-data/well.json");
You could inject the location of the file from your input control in place of the "sample-data/well.json" string.
Something like:
using Microsoft.AspNetCore.Components;
private async Task<List<MyData>> LoadFile(string filePath)
{
HttpClient _http;
// fetch data
// convert file data to MyData object
var results = await _http.GetJsonAsync<MyData[]>(filePath);
return results.ToList();
}

React native fetch... Explain it like I'm 5

export default class App extends Component {
state = {
data: []
};
fetchData = async () => {
const response = await fetch("https://randomuser.me/api?results=5"); // Replace this with the API call to the JSON results of what you need for your app.
const json = await response.json();
this.setState({ data: json.results }); // for the randomuser json result, the format says the data is inside results section of the json.
};
So, I have this code in my App.js file for React Native. The randomuser.me is a website that just gives you random users. Using it as a test URL right now. I don't really understand what the code is doing enough to be able to use it for other parts of my project. I was able to successfully display the 5 user results but now I want to access them again and iterate through the data attribute of the state.
tldr; Can I just access the data I got from the fetch in a for loop using data[i]? Please advise. I want to see if user input matches any of the items in the response that is stored in data attribute of state.
Ok the thign that you just did, that is fetch. You retrieve data from the internet.
"https://randomuser.me/api?results=5" is an API, there is lot of different API's, and each one has it´s own way to retrieve data from. if you put "https://randomuser.me/api?results=5" in your browser, you are gonna see a JSON, some API's store data in JSON, others in an array format.
In this case, the JSON, has just one child, 'results', thats why you store "json.results".
That´s fetch. The thing that you want to do is just javascript.
Store json.results in a variable
then iterate over it
var Results = json.results //store it in a variable
for(var i = 0;i<Object.keys(Results).length;i++){ //iterate
var CurrentUser = Results[Object.keys(Results)[i]] // i use this because some JSOn have random keys
if(CurrentUser.gender==='male'){//if you meet a condition
//do whatever you want
}
}
you can also use ".map" if it´s an array

Nancy return view as either a rendered view or unrendered file

I'm trying to do something slightly unusual in allowing for a file to be returned by Nancy as both a rendered view and as an unrendered file if requested. My code is similar to:
public class MyModule : NancyModule
{
public MyModule() : base("/apath")
{
Get["/{Name}"] = parameters =>
{
return View[parameters.Name];
};
Get["/{Name}/AsFile"] = parameters =>
{
return Response.AsFile(parameters.Name);
};
}
}
My files are stored relative to the application root in /Views/apath
Nancy works perfectly when returning the file as a View, but returns a NotFound http status code when trying to serve it as a file.
I've been trying to change the path passed to Response.AsFile, but no luck as yet.
How can I get the AsFile route working?
Nancy does not support this out of the box, with good reason.
The thing that is super scary about what you're trying to achieve is, if I passed in a url like:
..%2Fweb.config
I could return the config file back, get access to your connection strings, and basically hack your website.
What you want to do is have some sort of look up table in a database, or a flat file or something that allows you to correlate a name to a physical file.
Name Path
my-cat ../pictures/cat/my-cat.jpg
my-dog ../pictures/cat/my-dog.jpg
Then you can look up the name, return the filename, and then use that in your existing code:
Get["/{Name}/AsFile"] = parameters =>
{
var file = myFileService.GetFile(parameters.Name);
return Response.AsFile(file.Path);
};
Also if the file doesn't exist, then you know it might be an unsafe request and can tell the user to get lost!

Resources