I want to use this package. But I seem to be missing something. This is my code:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _image = File("assets/images/butterfly.jpg");
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
error: Cannot open file, path = 'assets/images/butterfly.jpg' (OS Error: No such file or directory, errno = 2).
How am I supposed to load an image with this?
I even tried to use Image from the get go. But no result. Maybe I am doing the File to Image conversion wrong?
**Update 1: **
class _HomePageState extends State<HomePage> {
final image = Image.asset('assets/images/butterfly.jpg');
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
image = geteditimage; // shows error asking to make the field not final
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(image).toCenter()) //The argument type 'Image' can't be assigned to the parameter type 'File'.
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
You need to add your asset directories to your pubspec.yaml.
For example:
dependencies:
...
dev_dependencies:
...
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
Then you can read the file as an image like so:
final image = Image.asset('assets/images/butterfly.jpg');
If you need to read the image as a file for the package you are trying to use, instead of coding in images, use a package like image_picker.
For your case:
class _HomePageState extends State<HomePage> {
File _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
Solution for this is error is to prevent the Image.file to read from null by setting a null check:
_image == null ? Container() : Image.file(_image).toCenter())
The app will build without error, and after that you can use the image editor pro to edit your image.
If anyone wants to pass image to editor page from image picker :
make changes to image_editor_pro.dart file
final Color appBarColor;
final Color bottomBarColor;
final Directory pathSave;
final double pixelRatio;
final File image;
ImageEditorPro(
{this.appBarColor,
this.bottomBarColor,
this.pathSave,
this.pixelRatio,
this.image});
#override
void initState() {
timers();
_controller.clear();
type.clear();
// fontsize.clear();
offsets.clear();
// multiwidget.clear();
howmuchwidgetis = 0;
_image = widget.image;
super.initState();
}
**Then use this code **
import 'package:flutter/material.dart';
import 'dart:io';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_editor_pro/image_editor_pro.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:firexcode/firexcode.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
// ignore: unnecessary_null_comparison
if (pickedFile != null) {
_image = File(pickedFile.path);
print("images : $_image");
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() async {
// ignore: unused_local_variable
final geteditimage =
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
image: _image,
);
})).then((geteditimage) {
print("image : $geteditimage");
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
}
#override
Widget build(BuildContext context) {
return condition(
// ignore: unnecessary_null_comparison
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse:
// ignore: unnecessary_null_comparison
_image == null ? Container() : Image.file(_image!).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTabText().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red))
.xRaisedButton(onPressed: () {
getimageditor();
});
}
}
Widget? condition({required bool condtion, Widget? isTrue, Widget? isFalse}) {
return condtion ? isTrue : isFalse;
}
Related
I am trying to use the image_picker on flutter app everything is fine until gallery open i choose the image then the app will crash and restart.
before this it was working fine like 1 month ago but now it is not. is there any solution
this is my code.
Future _pickImage() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
_image = imageTemporary;
});
} catch (error) {
print("error: $error");
}
// setState(() {
// _image = img;
// });
}
File? _image;
Future _pickImage() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
_image = imageTemporary;
});
} catch (error) {
print("error: $error");
}
}
This code snippet can help you.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PickImage extends StatefulWidget {
const PickImage({Key? key}) : super(key: key);
#override
State<PickImage> createState() => _PickImageState();
}
class _PickImageState extends State<PickImage> {
XFile? _image;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Column(
children: [
TextButton(
onPressed: _imageHandler, child: const Text("Pick image")),
if (_image != null) Image.file(File(_image!.path))
],
),
),
);
}
Future _imageHandler() async {
try {
final XFile? imagePicker =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (imagePicker != null) {
_image = imagePicker;
} else {
/// user canceled
}
} catch (e) {
print(e);
}
}
}
I want to implement that after clicking upload button it will pick image from gallery. After picking image then open Image cropper screen lastly cropped image will show in alert dialog. But here clicking upload button it pick image again clicking upload button open crop screen lastly clicking upload button it shows alert dialog.i want to change state automatically .. How can i fix that. Here is a sample code i have tried
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
late AppState state;
File? imageFile;
#override
void initState() {
super.initState();
state = AppState.free;
}
#override
Widget build(BuildContext context) {
Future pickedImage() async {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
imageFile = pickedImage != null ? File(pickedImage.path) : null;
if (imageFile != null) {
setState(() {
state = AppState.picked;
});
}
}
Future<Null> _cropImage() async {
var croppedFile = await ImageCropper().cropImage(
sourcePath: imageFile!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
imageFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
}
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
if (state == AppState.free)
pickedImage();
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) {
showAlertDialog(context);
} else {
Container();
}
},
child: Text("Upload"))
],
));
}
showAlertDialog(BuildContext context) {
// Create button
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
);
// Create AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Simple Alert"),
content: Container(
width: 250,
height: 100,
child: imageFile != null ? Image.file(imageFile!) : Container(),
),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
}
enum AppState {
free,
picked,
cropped,
}
Maybe you should add this line to setState block also.
if (croppedFile != null) {
//imageFile = croppedFile;
setState(() {
imageFile = croppedFile; //to here
state = AppState.cropped;
});
}
ImagePicker return a nullable CroppedFile?.
You can create a state variable to hold it.
File? imageFile;
CroppedFile? croppedFile;
/// you can also directly assing it on `croppedFile = await ImageCropper().cropImage(`
if (croppedFile != null) {
croppedFile = croppedFile;
setState(() {
state = AppState.cropped;
});
}
Now to view the croppedFile
croppedFile != null ? Image.file(File(croppedFile!.path)) : null),
I'm making an application to hide messages in pictures,
everything is running smoothly and i have declared everything, but there is a problem i'm having "LateError (LateInitializationError: Field 'image' has not been initialized.)". can anyone help me?
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:hideimage/action/decode_req.dart';
import 'package:hideimage/action/encode_req.dart';
import 'package:hideimage/fight/decode.dart';
import 'package:hideimage/fight/encode.dart';
import 'package:image_picker/image_picker.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final picker = ImagePicker();
late Uint8List image;
String text = "Example";
bool isLoading = false;
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
if (pickedFile != null) {
setState(() {
isLoading = true;
});
File _image = File(pickedFile.path);
EncodeRequest request =
EncodeRequest(_image.readAsBytesSync(), "", key: "");
image = await encodeMessageIntoImageAsync(request);
setState(() {
isLoading = false;
});
} else {
print('No Image Selected');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(text),
),
body: Center(
child: isLoading
? CircularProgressIndicator()
: image != null
? Text('No Image Selected')
: GestureDetector(
child: Image.memory(image),
onTap: () async {
setState(() {
isLoading = true;
});
DecodeRequest request = DecodeRequest(image, key: "");
text = await decodeMessageFromImageAsync(request);
setState(() {
isLoading = false;
});
},
)
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
you have a misunderstanding, late variables are not nullable, you are only telling the compiler that you will assign its value later but still before using it.
here you are checking if image != null so image has not been initialized yet, thus you get this error.
what you need here is making image nullable not late
i.e change the declaration to this
Uint8List? image;
I'm trying to make the image_editor_pro package in flutter to work using their example, but when I run the app, I get a lateintialization error '_image' has not been initialized , I tried replacing late with ? , but then I got another error since File type can't allow null values
The code :
import 'dart:io';
import 'package:image_editor_pro/image_editor_pro.dart';
import 'package:firexcode/firexcode.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late File _image;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
_image == null ? Container() : Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition(
{required bool condtion, required Widget isTrue, required Widget isFalse}) {
return condtion ? isTrue : isFalse;
}
You could use a boolean to check if _image has been initialized:
class _HomePageState extends State<HomePage> {
late File _image;
bool _isImageInitialized = false;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
_isImageInitialized = true;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _isImageInitialized == false,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Instead of using late File _image; you can use File? _image; which makes the _image variable nullable with default value null. Make sure to have proper null checks like (_image != null ) or (image?.method)
Full Code
import 'dart:io';
import 'package:image_editor_pro/image_editor_pro.dart';
import 'package:firexcode/firexcode.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.black87,
bottomBarColor: Colors.black87,
pathSave: null,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse:
_image == null ? Container() : Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition(
{required bool condtion, required Widget isTrue, required Widget isFalse}) {
return condtion ? isTrue : isFalse;
}
I'm new in Flutter and I want to save data into local file and load when open screen.
Any help?
You can use path_provider package. Here is example.
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
title: 'Reading and Writing Files',
home: FlutterDemo(storage: CounterStorage()),
),
);
}
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
class FlutterDemo extends StatefulWidget {
final CounterStorage storage;
FlutterDemo({Key key, #required this.storage}) : super(key: key);
#override
_FlutterDemoState createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
int _counter;
#override
void initState() {
super.initState();
widget.storage.readCounter().then((int value) {
setState(() {
_counter = value;
});
});
}
Future<File> _incrementCounter() {
setState(() {
_counter++;
});
// Write the variable as a string to the file.
return widget.storage.writeCounter(_counter);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Reading and Writing Files')),
body: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}