Image_picker not giving real path of the image in flutter - 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.

Related

how save theme or color of my flutter app

please any one help me when I close my app the theme reback to defult theme,how can I save the theme when I pick color from colorpicker library and I use hive library to save data,
if there are any another libraries to save data better than hive please tell me
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/src/block_picker.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter',
debugShowCheckedModeBanner: false,
//theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Box? box;
Color? z;
#override
void initState() {
super.initState();
openBox();
try {
getData();
} catch (e) {
print(e);
}
}
Future openBox() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('colorBox');
return;
}
void saveData(val) {
box!.put('color1', val);
}
void getData() {
setState(() {
z = Color(box!.get('color1'));
});
}
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
Color color = Colors.blue;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Counter"),
backgroundColor: z,
),
endDrawer: Drawer(
child: ListView(
children: [
ListTile(
title: Text("pick color"),
leading: Icon(Icons.color_lens),
onTap: () => showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text("select your color"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
BlockPicker(
onColorChanged: (Color value) {
saveData(value.value);
},
pickerColor: Colors.blue,
),
TextButton(
onPressed: () {
getData();
Navigator.pop(ctx);
},
child: Text("close"))
],
),
)),
),
],
),
),
body: Center(
child: Container(
width: double.infinity,
height: double.infinity,
child: TextButton(
onPressed: () {
incrementCounter();
},
child: Text(
'${counter}',),
),
),
),
);
}
}
I make code smaller as I can,and I remove all the style.
Hive should work for you,
alternatively you can use
Use the Shared Preference package and there you can store simple values as key pair values.Load that data in the init of the initial screen so that you can display the color as you need.
Step 1: Install flutter hive from https://pub.dev/packages/hive_flutter
Step 2: import 'package:hive_flutter/adapters.dart'; in your models
This class as of writing this answer contains two classes:
Color and TimeOfDay
Use hive. This is a benchmark blog that shows hive's performance capabilities: hive performance

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)
)
),
),

ImagePickerWeb Output is File$ instead of File

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),
),
);
}
}

How to get a picked file to show in a another widget

I wanted to build a feature where a user will be typing texts then may wanted to add a file, pick an image then the picked image will now be returned at the original text screen with the texts there too. I have develop the feature for inputting the texts my text feature then i am stuck at how the picked image will be returned to that same text place. Please how can i get this feature?
First You Need to Add dependencies image_picker: ^0.6.4 Used the latest version, Second
pickup an image
class _MyHomePageState extends State<MyHomePage> {
File _iamge;
Future CameraImage() async{
var iamge =await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_iamge = iamge;
});
}
Here Is Full Code To know Better Understand.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
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(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _iamge;
Future CameraImage() async{
var iamge =await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_iamge = iamge;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Container(
height: 500,
width: double.infinity,
color: Colors.blue,
child: _iamge==null?Center(child: Text("NO Image
Select")):Image.file(_iamge),
),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(onPressed: (){
CameraImage();
},child: Icon(Icons.camera),),
SizedBox(width: 20,),
FloatingActionButton(onPressed: (){},
child: Icon(Icons.photo_library),),
],
)
],
),
);
}
}
receive.dart
import 'package:flutter/material.dart';
import 'package:flutterapp/data.dart';
import 'package:provider/provider.dart';
class ReceiveData extends StatelessWidget {
#override
Widget build(BuildContext context) {
final providerdata= Provider.of<Data>(context);
return Scaffold(
body: Center(
child:
Text(providerdata.value.toString(),style:TextStyle(fontSize:50),),
),
);
}
}

Can't load an image from gallery with image_picker fails in Flutter

I'm quite newbie in Flutter,
I have wrote a simple app which opens the gallery, so the user will pick an image,
but both on emulator and physical device i get the same error:
════════ Exception caught by image resource service ════════
following assertion was thrown resolving an image codec: Unable to
load asset:
/data/user/0/com.example.upload_image_example/cache
/image_picker915145764706640017.jpg
Image provider: AssetImage(bundle: null, name:
"/data/user/0/com.example.upload_image_example/cache/image_picker915145764706640017.jpg")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#c486d(),
name:
"/data/user/0/com.example.upload_image_example/cache/image_picker915145764706640017.jpg",
scale: 1.0)
I have checked the path, the photo indeed exists in this path.
I have updated the pubspec.yaml for using other images in my assets directory.
but the problem arrives when i pick a photo with the image picker:
var photo = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
imageFile = photo;
});
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage(imageFile.path), // <---- HERE I receive the ERROR!!
);
}
}
What am I doing wrong?
Does anybody have some suggestion?
You can copy paste run full code below
You need FileImage
code snippet
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile),
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
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: '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> {
int _counter = 0;
File imageFile;
void _incrementCounter() async{
var photo = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
imageFile = photo;
});
setState(() {
_counter++;
});
}
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_ImageView(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
The problem is that Flutter interprets the images of the storage differently than the assets, you can solve it like this:
Widget _ImageView() {
if (imageFile == null) {
return CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('assets/images/avatar_blank.jpeg'),
);
} else {
return CircleAvatar(
radius: 80.0,
backgroundImage: FileImage(imageFile), // storageImage
);
}
}
This Worked for me: https://stackoverflow.com/a/60368338/8168140
simplified code is:
image: new DecorationImage(
image: FileImage(_image),
fit: BoxFit.cover,
),