I am using the camera to take a picture and save the picture on phones memory to later send it to AWS. I can take a picture and the path for the picture is there, but I am failing to create a file from the path using:
final imageFile = await File(path);
Why is the file not being created here? I always get 'Image file does not exist' on debug console.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class CameraPage extends StatefulWidget {
// 1
final CameraDescription? camera;
// 2
final ValueChanged? didProvideImagePath;
CameraPage({Key? key, this.camera, this.didProvideImagePath})
: super(key: key);
#override
State<StatefulWidget> createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage> {
CameraController? _controller;
Future<void>? _initializeControllerFuture;
#override
void initState() {
super.initState();
// 3
_controller = CameraController(widget.camera!, ResolutionPreset.medium);
_initializeControllerFuture = _controller?.initialize();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
// 4
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(this._controller!);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
// 5
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera), onPressed: _takePicture),
);
}
// 6
void _takePicture() async {
try {
await _initializeControllerFuture;
final tmpDirectory = await getTemporaryDirectory();
final filePath = '${DateTime.now().millisecondsSinceEpoch}.jpg';
final path = join(tmpDirectory.path, filePath);
await _controller?.takePicture();
widget.didProvideImagePath!(path);
final imageFile = await File(path);
if (imageFile.existsSync())
print('Image file exists');
else
print('Image file does not exist');
} catch (e) {
print(e);
}
}
// 7
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
}
takePicture method will return taken image as XFile, you can use the XFile path to create a File with taken Image path like below code.
File? imageFile;
XFile? xFile = await _controller?.takePicture();
if (xFile != null) {
imageFile = File(xFile.path);
}
if (imageFile != null && imageFile.existsSync()) {
print('Image file exists');
} else {
print('Image file does not exist');
}
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'm able to load file from my code. But the problem is, how to load the file from online server which is from this link- https://freevpn.gg/c/59.139.187.41/udp
My current code is-
var contennt=await rootBundle.loadString('assets/vpnconfig.ovpn');
You could use flutter cache manager to download the file and then read it. https://pub.dev/packages/flutter_cache_manager
String url = 'your_link';
final file = await DefaultCacheManager().getSingleFile(url);
var content = await file.readAsString();
dependencies:
flutter_filereader: ^2.2.0
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_filereader_example/file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
Permission.storage.request();
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String taskId;
Map<String, String> iosfiles = {
"docx": "assets/files/docx.docx", // IOS test
"doc": "assets/files/doc.doc", // IOS test
"xlsx": "assets/files/xlsx.xlsx", // IOS test
"xls": "assets/files/xls.xls", // IOS test
"pptx": "assets/files/pptx.pptx", // IOS test
"ppt": "assets/files/ppt.ppt", // IOS test
"pdf": "assets/files/pdf.pdf", // IOS test
"txt": "assets/files/txt.txt", // IOS test
"jpg": "assets/files/jpg.jpg", //
"jpeg": "assets/files/jpeg1.jpeg", //
"png": "assets/files/png.png", //
};
Map<String, String> androidfiles = {
"docx": "assets/files/docx.docx", // android test
"doc": "assets/files/doc.doc", // android test
"xlsx": "assets/files/xlsx.xlsx", // android test
"xls": "assets/files/xls.xls", // android test
"pptx": "assets/files/pptx.pptx", // android test
"ppt": "assets/files/ppt.ppt", // android test
"pdf": "assets/files/pdf.pdf", // android test
"txt": "assets/files/txt.txt" // android test
};
Map<String, String> files;
#override
void initState() {
if (Platform.isAndroid) {
files = androidfiles;
} else {
files = iosfiles;
}
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('File Reader'),
),
body: ListView.builder(
itemBuilder: (ctx, index) {
return item(files.keys.elementAt(index), files.values.elementAt(index));
},
itemCount: files.length,
),
);
}
item(String type, String path) {
return GestureDetector(
onTap: () {
onTap(type, path);
},
child: Container(
alignment: Alignment.center,
height: 50,
margin: EdgeInsetsDirectional.only(bottom: 5),
color: Colors.blue,
child: Center(
child: Text(
type,
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
);
}
onTap(String type, String assetPath) async {
String localPath = await fileLocalName(type, assetPath);
if (!await File(localPath).exists()) {
if (!await asset2Local(type, assetPath)) {
return;
}
}
Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
return FileReaderPage(
filePath: localPath,
);
}));
}
fileLocalName(String type, String assetPath) async {
String dic = await _localSavedDir() + "/filereader/files/";
return dic + base64.encode(utf8.encode(assetPath)) + "." + type;
}
fileExists(String type, String assetPath) async {
String fileName = await fileLocalName(type, assetPath);
if (await File(fileName).exists()) {
return true;
}
return false;
}
asset2Local(String type, String assetPath) async {
if (Platform.isAndroid) {
if (!await Permission.storage.isGranted) {
debugPrint("没有存储权限");
return false;
}
}
File file = File(await fileLocalName(type, assetPath));
if (await fileExists(type, assetPath)) {
await file.delete();
}
await file.create(recursive: true);
//await file.create();
debugPrint("文件路径->" + file.path);
ByteData bd = await rootBundle.load(assetPath);
await file.writeAsBytes(bd.buffer.asUint8List(), flush: true);
return true;
}
_localSavedDir() async {
Directory dic;
if (defaultTargetPlatform == TargetPlatform.android) {
dic = await getExternalStorageDirectory();
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
dic = await getApplicationDocumentsDirectory();
}
return dic.path;
}
}
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),
),
);
}
}
I'm trying to display the full camera display on this page and when I run it, it returns null. This is my first try, creating a camera page, so things might look all over the place.
StoryCamera.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
List<CameraDescription> cameras;
//CameraController controller;
class StoryCamera extends StatefulWidget {
final String currentUser;
StoryCamera({this.currentUser});
#override
_StoryCameraState createState() => _StoryCameraState();
}
class _StoryCameraState extends State<StoryCamera> {
CameraController _controller;
Future<void> _initializeControllerFuture;
bool isCameraReady = false;
bool showCapturedPhoto = false;
var ImagePath;
get pageStatus => 1;
#override
void initState() {
super.initState();
_initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
final firstCamera = cameras.first;
_controller = CameraController(firstCamera, ResolutionPreset.high);
_initializeControllerFuture = _controller.initialize();
if (!mounted) {
return Container();
}
setState(() {
isCameraReady = true;
});
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_controller != null
? _initializeControllerFuture = _controller.initialize()
: null; //on pause camera is disposed, so we need to call again "issue is only for android"
}
}
void onCaptureButtonPressed() async {
//on camera button press
try {
final path = join(
(await getTemporaryDirectory()).path, //Temporary path
'$pageStatus${DateTime.now()}.png',
);
ImagePath = path;
await _controller.takePicture(path); //take photo
setState(() {
showCapturedPhoto = true;
});
} catch (e) {
print(e);
}
}
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return Stack(
children: <Widget>[
Center(
child: Transform.scale(
scale: _controller.value.aspectRatio / deviceRatio,
child: new AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: new CameraPreview(_controller),
),
),
),
],
);
} else {
return Container(
child:
CircularProgressIndicator()); // Otherwise, display a loading indicator.
}
},
);
}
}
The error also points to the page before it that navigates you to this page.
StoryPage.dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StoryCamera())),
Can anyone tell me why this is happening?
You need to add a return
return FutureBuilder<void>(
In my flutter app, I store some images in cache directory and some files in application document directory, now I want to add possibility to my users to delete the cache dir and app dir,
How can I achieve this?
You need path_provider package
Then try this code:
Future<void> _deleteCacheDir() async {
final cacheDir = await getTemporaryDirectory();
if (cacheDir.existsSync()) {
cacheDir.deleteSync(recursive: true);
}
}
Future<void> _deleteAppDir() async {
final appDir = await getApplicationSupportDirectory();
if(appDir.existsSync()){
appDir.deleteSync(recursive: true);
}
}
This code may help you :
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),
),
);
}
}
Also, you can find very helpful document here:
https://github.com/flutter/samples/blob/master/INDEX.md