image picker Package is not working with me why? - flutter

I am using image_picker ^0.8.6+1 package for uploading a picture, after I added that dependency into the project, when I click in the floatingActionButton it suppose to open the image folder but it do nothing I don not know what wrong with my code, please help me with it :(
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(FourthUI());
class FourthUI extends StatefulWidget {
const FourthUI({super.key});
#override
State<StatefulWidget> createState() => _FourthUI();
}
class _FourthUI extends State<FourthUI> {
final ImagePicker _picker = ImagePicker();
File? pickedImage;
felchImage() async {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
if (image == null) {
return;
}
setState(() {
pickedImage = File(image.path);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
themeMode: ThemeMode.light,
theme: ThemeData(primarySwatch: Colors.blue, canvasColor: Colors.white),
title: 'my first UI application',
home: Scaffold(
appBar: AppBar(
title: Text(''),
),
body: Center(
child: pickedImage == null ? null : Image.file(pickedImage!),
),
floatingActionButton: FloatingActionButton(
onPressed: felchImage,
tooltip: 'Increment',
child: const Icon(Icons.photo_album),
),
));
}
}
I was expecting to open the image folder but when I click the FloatingActionButton nothing happen

Related

How to change theme in Flutter?

So I'm trying here to get the current theme, if it's light or dark.
So I can change widget color accordingly..
However, it doesn't work, I used if statment to know when it's dark mode..
but it's always False ..
This is the code.. btw it switch between dark & light theme..
but when i try to get current theme.. even if the theme changed to dark..
the if statments always show false...
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
bool darkModeOn = MediaQuery.of(context).platformBrightness == Brightness.dark;
Color containerColor;
if (darkModeOn == true) {
containerColor = Colors.blueGrey;
print("----------------");
print("dark mode ON");
print("----------------");
} else {
containerColor = Colors.deepPurple;
print("LIGHT mode ON");
}
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
//----switch theme---
currentTheme.switchTheme();
},
label: Text(
"Switch theme",
style: TextStyle(
),
),
icon: Icon(Icons.color_lens_outlined),
),
appBar: AppBar(
title: Text("DarkXLight"),
),
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(child: Container(
color: containerColor,
),
),
Expanded(child: Container(
color: Colors.amber,
),
),
],
),
),
);
}
}
You can't switch themes like that. You will need to handle the logic in the MaterialApp otherwise
MediaQuery.of(context).platformBrightness == Brightness.dark;
will always return true/false based on what was provided to the MaterialApp.themeMode.
Here's a sample code to get started. I used ValueListenableBuilder but you can also use provider.
Full code:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light);
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: _notifier,
builder: (_, mode, __) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: mode, // Decides which theme to show, light or dark.
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => _notifier.value = mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light,
child: Text('Toggle Theme'),
),
),
),
);
},
);
}
}
So, I was able to solve my problem..
I will put the code so if someone faced the same issue..
I simply, changed the way I used to switch themes. It was wrong..
However, here I'm posting the Correct way & this way solved the problem..
MAIN PAGE
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:practice_darkmode/theme_provider.dart';
import 'package:provider/provider.dart';
import 'MyHomePage.dart';
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ThemeProvider(),
builder: (context, _) {
final themeProvider = Provider.of<ThemeProvider>(context);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: MyThemes.lightTheme,
darkTheme: MyThemes.darkTheme,
themeMode: themeProvider.themeMode,
home: MyHomePage(),
);
},
);
}
}
Theme Provider class
import 'package:flutter/material.dart';
//---This to switch theme from Switch button----
class ThemeProvider extends ChangeNotifier {
//-----Store the theme of our app--
ThemeMode themeMode = ThemeMode.dark;
//----If theme mode is equal to dark then we return True----
//-----isDarkMode--is the field we will use in our switch---
bool get isDarkMode => themeMode == ThemeMode.dark;
//---implement ToggleTheme function----
void toggleTheme(bool isOn) {
themeMode = isOn ? ThemeMode.dark : ThemeMode.light;
//---notify material app to update UI----
notifyListeners();
}
}
//---------------Themes settings here-----------
class MyThemes {
//-------------DARK THEME SETTINGS----
static final darkTheme = ThemeData(
scaffoldBackgroundColor: Colors.black45,
// colorScheme: ColorScheme.dark(),
);
//-------------light THEME SETTINGS----
static final lightTheme = ThemeData(
scaffoldBackgroundColor: Colors.white,
//colorScheme: ColorScheme.light(),
);
}
Change Theme button widget class ( this is to create a switch button)
import 'package:flutter/material.dart';
import 'package:practice_darkmode/theme_provider.dart';
import 'package:provider/provider.dart';
class ChangeThemeButtonWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
//----First we want to get the theme provider----
final themeProvider = Provider.of<ThemeProvider>(context);
return Switch.adaptive(
//---isDarkMode to return if its dark or not--true or false--
value: themeProvider.isDarkMode,
onChanged: (value) {
final provider = Provider.of<ThemeProvider>(context, listen: false);
provider.toggleTheme(value);
},
activeColor: themeProvider.isDarkMode ? Colors.purple : Colors.green,
);
}
}
Home Page
import 'package:flutter/material.dart';
import 'package:practice_darkmode/theme_provider.dart';
import 'package:provider/provider.dart';
import 'ChangeThemeButtonWidget.dart';
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
dynamic text;
dynamic textColor;
dynamic appBarColor;
dynamic btnColor;
dynamic appBarTextColor;
if (Provider.of<ThemeProvider>(context).themeMode == ThemeMode.dark) {
text = "IT'S DARK ";
textColor = Colors.cyanAccent;
appBarColor = Colors.black;
btnColor = Colors.deepPurple;
appBarTextColor = Colors.cyanAccent;
} else if (Provider.of<ThemeProvider>(context).themeMode == ThemeMode.light) {
text = "IT'S LIGHT ";
textColor = Colors.red;
appBarColor = Colors.red;
btnColor = Colors.red;
appBarTextColor = Colors.white;
}
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
},
label: Text(
"Switch theme",
style: TextStyle(
),
),
icon: Icon(Icons.color_lens_outlined),
backgroundColor: btnColor,
),
appBar: AppBar(
title: Text("DarkXLight", style: TextStyle(color: appBarTextColor),),
backgroundColor: appBarColor,
actions: [
ChangeThemeButtonWidget(),
],
),
body: Container(
child: Center(
child: Text(
"$text!",
style: (
TextStyle(
fontSize: 27,
color: textColor,
)
),
),
),
),
);
}
}
Below code will to change theme via Icon Button in appBar. Steps:
Create a stateful widget.
Add the following variables:
bool _iconBool = false;
IconData _iconLight = Icons.wb_sunny;
IconData _iconDark = Icons.nights_stay;
Create actions -> IconButton in the appBar as below:
appBar: AppBar(
title: Text("Simple Colregs"),
backgroundColor: Color(0xFF5B4B49).withOpacity(0.8),
actions: [
IconButton(icon: Icon(_iconBool ? _iconDark : _iconLight),
},)
],
), //AppBar
Add Below methods with Light and Dark themes and any custom preference is required:
// light Theme
ThemeData lightThemeData(BuildContext context) {
return ThemeData.light().copyWith(
primaryColor: Color(0xFF5B4B49),
colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Color(0xFF24A751)));
}
// dark Theme
ThemeData darkThemeData(BuildContext context) {
return ThemeData.dark().copyWith(
primaryColor: Color(0xFFFF1D00),
colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Color(0xFF24A751)));
}
Read more about ThemeData Class here.
Under IconButton, create a functionality for the button as below which will toggle the theme:
onPressed: () {
setState(() {
_iconBool = !_iconBool;
});
Finally add under Material App:
theme: _iconBool ? lightThemeData(context) : darkThemeData(context),
That's all, good to go. Hope it helps.
you can use it in initState
bool darkModeOn = brightness == Brightness.dark;
or
var brightness = MediaQuery.of(context).platformBrightness;
bool darkModeOn = brightness == Brightness.dark;

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

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: Unhandled Exception: Unable to load asset

I am trying to build an app where one of the buttons should open a pdf. I used the guide in this link : https://pspdfkit.com/blog/2019/opening-a-pdf-in-flutter/ however it won't work on the first time the app is running it works only after a hot reload/restart. I have tried flutter clean. Also the output of the pubspec.yaml is exit code 0
flutter:
assets:
- PDFs/MyDoc.pdf
- assets/
Here is a snippet of the code:
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider/path_provider.dart';
const String _documentPath = 'PDFs/MyDoc.pdf';
void main() => runApp(MaterialApp(
home: FadyCard(),
));
class FadyCard extends StatefulWidget {
#override
_FadyCardState createState() => _FadyCardState();
}
class _FadyCardState extends State<FadyCard> {
Future<String> prepareTestPdf() async {
final ByteData bytes =
await DefaultAssetBundle.of(context).load(_documentPath);
final Uint8List list = bytes.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final tempDocumentPath = '${tempDir.path}/$_documentPath';
final file = await File(tempDocumentPath).create(recursive: true);
file.writeAsBytesSync(list);
return tempDocumentPath;
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
title: Text('Document'),
centerTitle: true,
backgroundColor: Colors.grey[850],
elevation: 0,
),
bottomNavigationBar: BottomAppBar(
shape: const CircularNotchedRectangle(),
child: Container(
height: 50.0,
),
color: Colors.grey[850],
),
floatingActionButton: FloatingActionButton(
onPressed: () => {
prepareTestPdf().then((path) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPdfViewerScreen(path)),
);
})
},
child: Icon(Icons.folder, color: Colors.amber,),
backgroundColor: Colors.grey[700],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
}
class FullPdfViewerScreen extends StatelessWidget {
final String pdfPath;
FullPdfViewerScreen(this.pdfPath);
#override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
title: Text("My Document"),
backgroundColor: Colors.grey[800],
),
path: pdfPath);
}
}
Thanks in advance.
FadyCard is the StateFull Widget you need update the PDF inside the setState.
Try like this (not tested)
onPressed: () => {
setState(() {
prepareTestPdf().then((path) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPdfViewerScreen(path)),
);
})
})
}