Untitled
unknown
plain_text
a year ago
2.6 kB
2
Indexable
Never
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ImagePickerDemo extends StatefulWidget { @override _ImagePickerDemoState createState() => _ImagePickerDemoState(); } class _ImagePickerDemoState extends State<ImagePickerDemo> { File? _image; @override void initState() { super.initState(); _loadImageFromPrefs(); } Future<void> _pickImage(ImageSource source) async { final picker = ImagePicker(); final pickedFile = await picker.getImage(source: source); if (pickedFile != null) { final appDirectory = await getApplicationDocumentsDirectory(); final imageFile = File(pickedFile.path); // Generate a unique filename for the image final imageName = 'selected_image_${DateTime.now().millisecondsSinceEpoch}.jpg'; final imagePath = '${appDirectory.path}/$imageName'; // Copy the selected image to local storage await imageFile.copy(imagePath); // Save the image path to shared preferences final prefs = await SharedPreferences.getInstance(); prefs.setString('imagePath', imagePath); setState(() { _image = File(imagePath); }); } } Future<void> _loadImageFromPrefs() async { final prefs = await SharedPreferences.getInstance(); final imagePath = prefs.getString('imagePath'); if (imagePath != null) { setState(() { _image = File(imagePath); }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Image Picker Demo'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ if (_image != null) Image.file( _image!, width: 200.0, height: 200.0, ) else Text('No image selected'), SizedBox(height: 20.0), ElevatedButton( onPressed: () { _pickImage(ImageSource.gallery); }, child: Text('Pick Image from Gallery'), ), ElevatedButton( onPressed: () { _pickImage(ImageSource.camera); }, child: Text('Take a Photo'), ), ], ), ), ); } }