i am learning imagepicker from https://pub.dev/packages/image_picker ,
but i don't why i got an error when i have use the way step by step.
this is the problem :
first, i declare a File variable
File _imageFile ;
then i use it in a method,
_getimg() async{
var _img = await ImagePicker(source: ImageSource.gallery);
setState(() {
_imageFile = _img ;
});
}
and then i got this error :
A value of type 'File (where File is defined in
D:\Flutter\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)' can't
be assigned to a variable of type 'File (where File is defined in
D:\Flutter\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)'.
There is a conflict between Files declaration. The html package has one declaration of a class File and the io package has another declaration (same name, different origin).
In fact, using html is for web and io is used for console, server or mobile apps, so check your imports and delete io or html depending in the type of project you are working on.
Another solution is to define your imports like this:
import 'package:html/html.dart' as h; //"h" can change, is just an example
import 'dart:io' as i; //"i" also can be another char or word, is just an example
//And when you need to create a File,
//you can decide if you want to create
//an io File or an html File
main(){
i.File f1 = ...; //The io File, starting with "i."
h.File f2 = ...; //The html File, starting with "h."
}
Related
Problem Explanation
I have a file that looks like this:
myfile1.txt
[
{
"question": "Thanks for the help",
"answer choices": [
"Hi",
"stack",
"over",
"flow",
],
},
...
]
This file contains data that needs to be set to a variable in a separate Dart file. The file type of this data does not matter, so if a .dart file would be easier to work with that would be perfectly fine.
Example of dart file that calls for the above file:
main.dart
void main() {
List<Map<String, dynamic>> data;
for (int i=0; i<5; i++) {
data = getFile("myfile$i.txt");
// Does stuff here
}
}
Note: getFile() does not actually have to be used. It's just a placeholder for the example.
Question: How would I set the data in this file to the variable data while in a function (like main()).
My attempt
Ideally, I wouldn't want to make many changes to the data file but here is what I did:
myfile1.dart
List<Map<String, dynamic>> data = [
...
]
I changed the file type to a .dart file and created a variable that would be set to the data.
I then modified my main.dart file like so:
main.dart
void main() {
for (int i=0; i<5; i++) {
import "myfile$i.dart";
// Does stuff here
}
}
This approach fails because import cannot be called from inside a function.
You can't use the word import there. It's reserved word, used for loading flutter/dart packages, class files, etc. It's not for "loading" some arbitrary data from a file.
Flutter official website has a cookbook example for reading and writing data from and to files. Perhaps their example would work for you?
This isn't JavaScript. Before any of the program is running, all the potential Dart code must have already been compiled. You don't get to keep compiling Dart into anything after the first step of main() is active.
I'm trying to find a package which would recognise file type. For example
final path = "/some/path/to/file/file.jpg";
should be recognised as image or
final path = "/some/path/to/file/file.doc";
should be recognised as document
You can make use of the mime package from the Dart team to extract the MIME types from file names:
import 'package:mime/mime.dart';
final mimeType = lookupMimeType('/some/path/to/file/file.jpg'); // 'image/jpeg'
Helper functions
If you want to know whether a file path represents an image, you can create a function like this:
import 'package:mime/mime.dart';
bool isImage(String path) {
final mimeType = lookupMimeType(path);
return mimeType.startsWith('image/');
}
Likewise, if you want to know if a path represents a document, you can write a function like this:
import 'package:mime/mime.dart';
bool isDocument(String path) {
final mimeType = lookupMimeType(path);
return mimeType == 'application/msword';
}
You can find lists of MIME types at IANA or look at the extension map in the mime package.
From file headers
With the mime package, you can even check against header bytes of a file:
final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg
There is no need of any extension. You can try below code snippet.
String getFileExtension(String fileName) {
return "." + fileName.split('.').last;
}
If think you should take a look to path package, specially to extension method.
You can get file format without adding one more package to pubspec.yaml ;)
context.extension('foo.bar.dart.js', 2); // -> '.dart.js
context.extension('foo.bar.dart.js', 3); // -> '.bar.dart.js'
context.extension('foo.bar.dart.js', 10); // -> '.bar.dart.js'
context.extension('path/to/foo.bar.dart.js', 2); // -> '.dart.js'
Assume I have a flutter test file foo_test.dart with:
void main() {
final file = ...how to get the path of this file... 'foo_test.dart';
...
}
How can I achieve that?
The following snippet allows to retrieve the file containing main():
final mainFile = Uri.parse(RegExp(r'#.*main \((.*):.*:.*\)')
.firstMatch(StackTrace.current.toString())
.group(1))
.toFilePath();
I can load one file and traverse it with babel, it goes something like this:
var babylon = require("babylon");
let contents = fs.readFileSync("example.js","utf-8");
let ast = babylon.parse(contents);
Now the question is, how can I get the AST (Abstract Syntax Tree) if I have multiple files in my program.
main.js
export const getFoo(){
return "a"
}
example.js
import {getFoo} from './main'
let bar = getFoo() + "baz";
Obviously I would like to see the function declaration and the function call expression into the same AST, but also at the same time getting the line numbers and columns (node.loc) information to also show the specific file.
You can concatenate the AST from several files if you know their paths and can load them.
import {parse} from '#babel/parser';
const a = 'var a = 1;'; // or fs.readFileSync("a.js","utf-8");
const b = 'var b = 2;'; // or fs.readFileSync("b.js","utf-8");
const astA = parse(a, { sourceFilename: 'a.js' });
const astB = parse(b, { sourceFilename: 'b.js' });
const ast = {
type: 'Program',
body: [].concat(astA.program.body, astB.program.body)
};
Source example
But I can't find out how to get AST from several files without loading them directly. I tried to write a babel plugin to analyze code from an imported file and I haven't realized how to do that.
I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename