ImagePickerWeb Output is File$ instead of File - flutter

I am using ImagePickerWeb to allow users to upload photos from my app
Future<void> getPhotos() async {
var imageFile = await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
When I try to display the image via Image.File
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
),
I get this error
File$ ([object File]) :<getObject: NoSuchMethodError: The
getter 'uri' was called on null.>
I am using the file format for my because I am passing the image to my back end server and it receives the data as a file. Any help would be appreciated.

You can copy paste run full code below
According to owner's description https://github.com/Ahmadre/image_picker_web#how-do-i-get-all-informations-out-of-my-imagevideo-eg-image-and-file-in-one-run
You can use ImagePickerWeb.getImageInfo and show image with Image.memory
code snippet
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
...
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
working demo
full code
import 'dart:async';
import 'dart:io';
import 'package:mime_type/mime_type.dart';
import 'package:path/path.dart' as Path;
import 'package:flutter/material.dart';
import 'package:image_picker_web/image_picker_web.dart';
import 'dart:html' as html;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var currentSelfie;
Future<void> getPhotos() async {
var mediaData = await ImagePickerWeb.getImageInfo;
String mimeType = mime(Path.basename(mediaData.fileName));
html.File mediaFile =
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});
print("imageFile ${mediaData.toString()}");
if (mediaData != null) {
currentSelfie = mediaData.data;
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
currentSelfie == null
? Container()
: Image.memory(
(currentSelfie),
fit: BoxFit.fill,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getPhotos,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Related

Displaying a created PDF in a new tab for flutter web

I am currently creating a PDF to display inputted data from the user and I want to display the pdf in a new tab so they can either print it or download it or just close out.
The current PDF creation method is:
Future<void> createPDF() async{
final PdfDocument document = PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 20),
brush: PdfSolidBrush(PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, '$NewConfig.pdf');
}
then to open the file I have this method:
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
PdfView(controller: pdfController);
}
The issue I am running into is the new tab that opens displays this:
37806870454946551310371311462502541310493248321119810613106060131047841211121013247679711697108111103131047809710310111532503248328213106262131010111010011198106131050324832111981061310606013104784121112101324780971031011151310477510510011532915132483282931310476711111711011632491310478210111511111711499101115326060626213101310477710110010597661111203291483248325357533256525093131062621310101110100111981061310513248321119810613106060131047671111171101163249131047841211121013247809710310111513104775105100115329152324832829313104780971141011101163250324832821310626213101011101001119810613105232483211198106131060601310478412111210132478097103101131047809711410111011632513248328213104767111110116101110116115329153324832823254324832823255324832829313104782101115111117114991011153260601310478011411199831011163291478068703247841011201169313104770111110116326060131047994998565353545345534851514552101565345985399504553565154485748981015048513256324832821310626213101310626213101310626213101011101001119810613105332483211198106131060601310477010510811610111432477010897116101681019911110010113104776101110103116104325713106262131011511611410197109131012094434001140114131010111010011511611410197109131010111010011198106131054324832111981061310606013104770105108116101114324770108971161016810199111100101131047761011101031161043257131062621310115116114101971091310120941140082082131010111010011511611410197109131010111010011198106131055324832111981061310606013104770105108116101114324770108971161016810199111100101131047761011101031161043250505713106262131011511611410197109131012094101143657534916133239129252135241322146718217921720554949169175213642071871051869320038539138254122147698014597301321532472302034337215176592471105216061243225561856225136314915325146710778105157252165162164620485841822824418812023711612918515227228989410517881108111961551426748148156415712843203422444621814625525521417525223914411496171408922315518373155231199452369425460117164423832424364215131201621976962111762147219361615719178233240147195177114221341688311317017616894244613148201231158207322789229127168204178122502141225624896143871835514860100184613795972178011310101110100115116114101971091310101110100111981061310563248321119810613106060131047841211121013247701111101161310478311798116121112101324784121112101491310476697115101701111101163247721011081181011161059997131047691109911110010511010332478710511065110115105691109911110010511010313106262131010111010011198106131012011410110213104832571310484848484848484848483254535351533210213104848484848484848495532484848484832110131048484848484848485550324848484848321101310484848484848484956483248484848483211013104848484848484850535732484848484832110131048484848484848525256324848484848321101310484848484848485351543248484848483211013104848484848484854505232484848484832110131048484848484848575152324848484848321101310116114971051081011141310606013104782111111116324932483282131047831051221013257131062621310131011511697114116120114101102131049485157131037376979701310
which I am guessing is the bytes but am at a loss as to what I am supposed to do from here.
any info?
I suggest you to directly use a pub package like native_pdf_view.
Its easyer than your method in my opinion and you dont need to reinvente the wheel.
EDIT:
Here is a code that i do quickly, it can be improve with a ChangeNotifier etc... to handle Future function, But it work.
main.dart
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart' as scPdf;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late PdfController _pdfController;
bool isPdfLoaded = false;
Future<void> createPDF() async{
final scPdf.PdfDocument document = scPdf.PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', scPdf.PdfStandardFont(scPdf.PdfFontFamily.helvetica, 20),
brush: scPdf.PdfSolidBrush(scPdf.PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, 'test.pdf');
}
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
setState(() {
isPdfLoaded = true;
_pdfController = pdfController;
});
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'PDF',
),
isPdfLoaded ? Container(width : size.width, height: size.height * 0.5, child : PdfView(controller: _pdfController)) : Text("Pdf not loaded"),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: createPDF,
tooltip: 'CreatePDF',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Re-EDIT:
This is the exemple using Navigator.push to display the pdf in another page:
main.dart
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
import 'package:stackoverflow/pdf_view.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart' as scPdf;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late PdfController _pdfController;
bool isPdfLoaded = false;
Future<void> createPDF() async{
final scPdf.PdfDocument document = scPdf.PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', scPdf.PdfStandardFont(scPdf.PdfFontFamily.helvetica, 20),
brush: scPdf.PdfSolidBrush(scPdf.PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, 'test.pdf');
}
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
await Navigator.of(context).push((MaterialPageRoute(builder: (context) => PdfViewPage(pdfController: pdfController))));
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Click on Floating button to create and open your pdf in another view',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: createPDF,
tooltip: 'CreatePDF',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
pdf_view.dart
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
class PdfViewPage extends StatelessWidget {
const PdfViewPage({Key? key, required this.pdfController}) : super(key: key);
final PdfController pdfController;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: PdfView(controller: pdfController)
),
);
}
}

Why images didn't add to the imagescontainer in ListView

This is my code
If I push the button the image is showing after I press the "hot reload" button.
Question:
Why can't the images be added to the imagecontainer in ListView?
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Anime Randomizer'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var urlresult = "https://danbooru.donmai.us/data/original/13/c4/13c4ee9c0f8e305fbe6a4c4efb540ec7.jpg";
var filter = "";
var error = "";
var iterator = 0;
List<Widget> imagescontainer = [new Container(child: Image.network("https://danbooru.donmai.us/data/original/13/c4/13c4ee9c0f8e305fbe6a4c4efb540ec7.jpg", width: 400, height: 650)),];
void fetchAnimeUrl() async {
var url = Uri.parse('https://danbooru.donmai.us/posts/random?tags=rating%3Asafe${filter != null ? '+'+filter: ''}&format=json');
final response = await http.get(url);
if (response.statusCode == 200) {
var start = response.body.indexOf('file_url');
var end = response.body.indexOf(',"large_file_url"');
if(start != -1 || end != -1){
setState(() {
iterator++;
urlresult = response.body.substring(start + 11, end - 1);
error = imagescontainer.length.toString();
imagescontainer.add(new Container(child: Image.network(urlresult.toString(), width: 300, height: 620)));
});
}
else{
setState(() {
error = "Купить премиум - 25\$";
});
}
} else {
throw Exception('Failed to load anime');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Anime randomizer list"),
),
body: Container(
child: ListView(
scrollDirection: Axis.vertical,
children: imagescontainer //this variable contain all my images
),
),
floatingActionButton: FloatingActionButton(
onPressed: fetchAnimeUrl,
tooltip: 'MoreAnime',
child: Icon(Icons.arrow_circle_down),
),
);
}
}
I fix it!
body: Container(
child: ListView(
scrollDirection: Axis.vertical,
children: imagescontainer.toList() //i wrote a "toList()"
),
),

Flutter: Adding background image with image picker

so I have a simple question that I can't seem to figure out after a lot of trying out different things. So I have this ImagePicker Flutter function that picks image from gallery. I want to be able to click button to change background of the whole screen. Here is the function for Image Picker and it works fine.
Future _getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
print('_image: $_image');
} else {
print('No image selected');
}
});
}
The issue is that I can't seem to add that picked image in the BoxDecoration in the Scaffold, there is always an error, something in the vein of: 'The argument type 'Image' can't be assigned to the parameter type 'ImageProvider'
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: Image(_image),
),
),
I tried converting to string, linking direct path, but nothing seems to work. Is there a workaround around this or is there some other simple solution? Thank you!
You can copy paste run full code below
You can check _image == null and to show TransparentImage or FileImage
code snippet
import 'package:transparent_image/transparent_image.dart';
...
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _image == null
? MemoryImage(kTransparentImage)
: FileImage(_image),
),
)),
working demo
full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
final picker = ImagePicker();
Future _getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
print('_image: $_image');
} else {
print('No image selected');
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _image == null
? MemoryImage(kTransparentImage)
: FileImage(_image),
),
)),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
please try this ...
Container(
width: 100,
height: 200,
decoration: BoxDecoration(
image:DecorationImage(
image: new FileImage(file)
)
),
),

Image_picker not giving real path of the image in flutter

I want to select image from gallery, but when I tried to save it in shared preferences. I found that image_picker gives temporary location like tmp/image_picker_4415467867A964-791E-4AFA995BA-18295-0003861F9255294A.jpg
This is not real path of the image. How should I get original location path of the image for later use?
Or I want to save the whole image in database.. what to do?
pickimage() is deprecated now?
Please help
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fluter demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
String _imageloc;
#override
void initState() {
super.initState();
LoadImage();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker'),
),
body: Container(
alignment: Alignment.center,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_imageloc != null
? CircleAvatar(
backgroundImage: FileImage(File(_imageloc)),
radius: 80,
)
: CircleAvatar(
backgroundImage: _image != null
? FileImage(_image)
: NetworkImage(
'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png'),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {
PickImage();
},
child: Text('Pick Image'),
),
),
RaisedButton(
onPressed: () {
saveImage(_image.path);
},
child: Text('saved'),
),
],
),
),
);
}
void PickImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
print(image.path);
setState(() {
_image = image;
});
}
void saveImage(_imageloc) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
preferences.setString('imageloc', _imageloc);
});
}
void LoadImage() async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
setState(() {
saveimage.getString('imageloc');
});
}
}
Well, if you need the image later, you need to copy it and save it somewhere. The actual image, not just the path. If I select an image in your app, I want it to be saved. I don't want it to be gone when I delete the picture from my gallery, or switch phones.
The path you have is sufficient to read the image and save it wherever you want. Your backend most likely, since I want to have my picture, even on another phone.
How you do this is highly dependent on your specific backend, but I'm sure there will be a tutorial for it.

Flutter image picker won't show up in Android 10

I am a beginner in flutter. I was checking to use image_picker in flutter. But When I tried to check image_picker with my Andorid Phone (10) it won't show up. I don't know what happened, I have added android:requestLegacyExternalStorage="true" in AndroidManifest.xml,
still no change, I don't know what to do? Please help me
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _fileimage;
final _picker = ImagePicker();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_fileimage != null
? FileImage(_fileimage)
: Text('No image selected'),
RaisedButton(
onPressed: () => _takePicture,
child: Text('hi'),
)
],
),
),
),
);
}
void _takePicture() async {
final pickedImage = await _picker.getImage(source: ImageSource.gallery);
// if (pickedImage == null) {
// return;
// }
File tmpFile = File(pickedImage.path);
final Directory directory = await getApplicationDocumentsDirectory();
final String path = directory.path;
final String fileName =
basename(pickedImage.path); // Filename without extension
final String fileExtension = extension(pickedImage.path); // e.g.
tmpFile = await tmpFile.copy('$path/$fileName$fileExtension');
setState(() => _fileimage = tmpFile);
}
}
I found problem with your code.
You used 'FileImage' in 'Widget' is required. Because 'FileImage' returns 'ImageProvider', you should use 'Image.file()' instead of 'FileImage'.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _fileimage;
final _picker = ImagePicker();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_fileimage != null
? Image.file(_fileimage)
: Text('No image selected'),
RaisedButton(
onPressed: () async {
_takePicture();
},
child: Text('hi'),
)
],
),
),
),
);
}
void _takePicture() async {
final pickedImage = await _picker.getImage(source: ImageSource.gallery);
// if (pickedImage == null) {
// return;
// }
File tmpFile = File(pickedImage.path);
final Directory directory = await getApplicationDocumentsDirectory();
final String path = directory.path;
final String fileName =
basename(pickedImage.path); // Filename without extension
final String fileExtension = extension(pickedImage.path); // e.g.
tmpFile = await tmpFile.copy('$path/$fileName$fileExtension');
setState(() => _fileimage = tmpFile);
}
}