Store Image in List<Xfile> from image urls - flutter

I have created a variable
List<Xfile> imageList;
using this variable I have showed the selected images in GridView.Builder and uploaded them.
But I want to store those uploaded images in this List to show them again in GridView.Builder.
Means How to store images from imageUrls in List
How can I achieve this?

Follow as follows:
Variables
final picker = ImagePicker();
File? file;
XFile? pickedImage;
bool isLoading = false;
List<File?> fileList = [];
Method to select image from gallery
Future pickImageFromGallery() async {
pickedImage = await picker.pickImage(source: ImageSource.gallery);
setState(() {
file = File(pickedImage!.path);
fileList.add(file);
});
}
And place in gridview as follows:
GridView.builder(
itemCount: fileList.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int i) {
return Container(
padding: const EdgeInsets.all(10),
child: Stack(
children: <Widget>[
SizedBox(
height: 100,
width: 100,
child: Image.file(File(fileList[i]!.path),fit: BoxFit.cover,),
),
Positioned(
right: 1,
child: GestureDetector(
onTap: () {
setState(() {
dltImages(fileList[i]);
});
},
child: const Icon(Icons.cancel, color: Colors.red),
))
],
),
);
},
),
Find full code at:
https://github.com/nbnD/image_picker_flutter/blob/master/lib/homepage.dart

I do like this if there is multi images upload
class PickImagesPage extends StatefulWidget {
const PickImagesPage({super.key, required this.initialUrls});
final List<String> initialUrls;
#override
State<PickImagesPage> createState() => _PickImagesPageState();
}
class _PickImagesPageState extends State<PickImagesPage> {
#override
void initState() {
urls = widget.initialUrls;
super.initState();
}
List<String> urls = [];
List<File> files = [];
List<String> removedUrls = [];
final Repo repo = Repo();
#override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme;
final scheme = theme.colorScheme;
return LoadingLayer(
child: Scaffold(
bottomNavigationBar: Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: ElevatedButton(
onPressed:
files.isNotEmpty || widget.initialUrls.length != urls.length
? () async {
try {
await repo.uploadImages(
files: files,
urls: urls,
removedUrls: removedUrls,
);
Navigator.pop(context);
} catch (e) {
AppSnackbar(context).error(e);
if (kDebugMode) {
print(e);
}
}
}
: null,
child: const Text(Labels.save),
),
),
appBar: AppBar(
title: const Text(
Labels.ambienceImages,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final List<XFile> pickedFiles = await pickImages();
if (pickedFiles.isNotEmpty) {
setState(() {
files.addAll(pickedFiles.map((e) => File(e.path)));
});
}
},
child: const Icon(Icons.add),
),
body: GridView.count(
padding: const EdgeInsets.all(12),
crossAxisCount: 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
children: [
...urls
.map(
(e) => GestureDetector(
onTap: () {
setState(() {
urls.remove(e);
removedUrls.add(e);
});
},
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: NetworkImage(e),
),
),
),
),
)
.toList(),
...files
.map(
(e) => Container(
clipBehavior: Clip.antiAlias,
alignment: Alignment.topRight,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: FileImage(e),
),
),
child: SizedBox(
height: 40,
width: 40,
child: RawMaterialButton(
elevation: 0,
focusElevation: 0,
hoverElevation: 0,
shape: const CircleBorder(),
fillColor: theme.cardColor.withOpacity(0.5),
onPressed: () {
setState(() {
files.remove(e);
});
},
child: const Icon(Icons.remove),
),
),
),
)
.toList(),
GestureDetector(
onTap: () async {
final List<XFile> pickedFiles = await pickImages();
if (pickedFiles.isNotEmpty) {
setState(() {
files.addAll(pickedFiles.map((e) => File(e.path)));
});
}
},
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
),
child: Stack(
children: const [
Center(
child: Icon(Icons.add),
),
PickImageLabel(),
],
),
),
),
],
),
),
);
}
}
class Repo {
Future<void> uploadImages(
{required List<String> urls,
required List<File> files,
required List<String> removedUrls}) async {
List<String> newUrls = [];
for (var file in files) {
final url = await upload(file);
newUrls.add(url);
}
for (var url in removedUrls) {
await deleteImage(url);
}
await saveImages(urls + newUrls);
}
}

Related

Error : Failed to detect image file format using the file header. File header was [0x3c 0x68 0x74 0x6d 0x6c 0x3e 0x0a 0x20 0x20 0x20]

I'm trying to display an image from Firestore in to my UI. But it returns the error above, and the file format also changes when I run it on Edge (not on physical device or Emulator). I can't figure out how. Here's my code.
class ViewPola extends StatefulWidget {
const ViewPola({Key? key}) : super(key: key);
static String id = 'view_pola';
#override
State<ViewPola> createState() => _ViewPolaState();
}
class _ViewPolaState extends State<ViewPola> {
Function getSnaps = () async {
final polaMap = {
'Kode Pola': '',
'Bagian Pola': '',
'image_url': '',
};
FirebaseFirestore.instance
.collection('PolaWillyJKT')
.limit(1)
.get()
.then((snapshot) {
if (snapshot.size == 0) {
FirebaseFirestore.instance.collection('PolaWillyJKT').add(polaMap);
FirebaseFirestore.instance.collection('PolaWillyJKT');
print('add');
} else {
print('disini nge get');
var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
Map<String, dynamic> data = a as Map<String, dynamic>;
print(data);
}
});
};
var _selectedItem;
var _showList = false;
#override
void initState() {
getSnaps();
super.initState();
}
final Stream<QuerySnapshot> _polaWilly =
FirebaseFirestore.instance.collection('PolaWillyJKT').snapshots();
#override
Widget build(BuildContext context) {
final screenHeight = ScreenInfo.screenHeight(context);
final screenWidth = ScreenInfo.screenWidth(context);
return StreamBuilder<QuerySnapshot>(
stream: _polaWilly,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return SafeArea(
child: Scaffold(
body: Padding(
padding: EdgeInsets.all(25),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Pilih Bagian Pola',
style: TextStyle(fontSize: 25),
),
const SizedBox(
height: 20,
),
DropdownButton(
isExpanded: true,
value: _selectedItem,
items: snapshot.data?.docs
.map(
(value) => DropdownMenuItem(
value: value.get("Bagian Pola"),
child: Text('${value.get("Bagian Pola")}'),
),
)
.toList(),
onChanged: (newValue) {
setState(() {
_selectedItem = newValue.toString();
_showList = true;
});
}),
Padding(
padding: const EdgeInsets.all(25),
child: Visibility(
visible: _showList,
child: Container(
height: screenHeight * 0.4,
child: ListView(
children: snapshot.data!.docs
.where(
(e) => e.get("Bagian Pola") == _selectedItem)
.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Center(
child: Column(
children: [
Text(
'Bagian Pola: ${data["Bagian Pola"]}',
style: TextStyle(fontSize: 15),
),
const SizedBox(
height: 15,
),
Text(
'Kode Pola : ${data["Kode Pola"]}',
style: TextStyle(fontSize: 15),
),
const SizedBox(
height: 15,
),
Image(
image:
NetworkImage(document.get("Foto Pola")),
height: 200,
width: 200,
), // this is the Image widget where I tried to put the image from firestore
Text(document.get('Foto Pola').toString()),
],
),
);
}).toList(),
),
),
),
),
],
),
),
),
);
},
);
}
}
and here's the class that uploads the image to Firestore
class Input_Pola extends StatefulWidget {
const Input_Pola({Key? key}) : super(key: key);
static String id = 'input_pola';
#override
State<Input_Pola> createState() => _Input_PolaState();
}
class _Input_PolaState extends State<Input_Pola> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
void _checkDuplicate() {
if (options.contains(_textfieldValue.text)) {
// Display bottom sheet that says item already exists
_scaffoldKey.currentState?.showBottomSheet((context) => Container(
height: 300,
child: Column(
children: [
const Text('Item already exists'),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Dismiss'))
],
),
));
} else {
// Add item to options list
setState(() {
options.add(_textfieldValue.text);
});
}
}
XFile? image;
final ImagePicker picker = ImagePicker();
String _image_url = '';
void _addToFirebase(String dropdownValue, String _kodePolaController) {
var imageFile = File(image!.path);
String fileName = pth.basename(imageFile.path);
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child("WillyJKT/polaWillyJKT");
UploadTask uploadTask = ref.putFile(imageFile);
uploadTask.whenComplete(() async {
var url = await ref.getDownloadURL();
_image_url = url.toString();
});
FirebaseFirestore.instance
.collection('PolaWillyJKT')
.doc(_selectedOption)
.set({
'Bagian Pola': _selectedOption,
'Kode Pola': _kodePolaController,
'Foto Pola': _image_url
});
}
String _dropdownValue = 'kg';
String _property1 = '';
String _property2 = '';
String _property3 = '';
bool _isOptionSelected = false;
final TextEditingController _kodePolaController = TextEditingController();
var _selectedOption;
final TextEditingController _textfieldValue = TextEditingController();
final List<String> options = [];
#override
void initState() {
super.initState();
_selectedOption = options.isNotEmpty ? options[0] : null;
}
//we can upload image from camera or from gallery based on parameter
Future getImage(ImageSource media) async {
var img = await picker.pickImage(source: media);
setState(() {
image = img;
});
}
void myAlert() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
title: Text('Please choose media to select'),
content: Container(
height: MediaQuery.of(context).size.height / 6,
child: Column(
children: [
ElevatedButton(
//if user click this button, user can upload image from gallery
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.gallery);
},
child: Row(
children: [
Icon(Icons.image),
Text('From Gallery'),
],
),
),
ElevatedButton(
//if user click this button. user can upload image from camera
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.camera);
},
child: Row(
children: [
Icon(Icons.camera),
Text('From Camera'),
],
),
),
],
),
),
);
});
}
#override
Widget build(BuildContext context) {
final screenHeight = ScreenInfo.screenHeight(context);
final screenWidth = ScreenInfo.screenWidth(context);
return SafeArea(
child: Scaffold(
key: _scaffoldKey,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
_addToFirebase(_dropdownValue, _kodePolaController.text);
},
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(25),
child: Container(
height: screenHeight,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextFormField(
decoration: const InputDecoration(
hintText: 'Input Pola',
border: UnderlineInputBorder(),
),
onChanged: (value) {
setState(() {
_textfieldValue.text = value;
});
},
),
DropdownButton<String>(
value: _selectedOption,
onChanged: (value) {
setState(() {
_selectedOption = value!;
_isOptionSelected = true;
_kodePolaController.clear();
});
},
hint: const Text('Input from Text Field Above'),
items: options.map((option) {
return DropdownMenuItem<String>(
value: option,
child: Text(option),
);
}).toList(),
),
TextButton(
onPressed: _checkDuplicate,
child: const Text("Add Option"),
),
Visibility(
visible: _isOptionSelected,
child: Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
TextField(
controller: _kodePolaController,
decoration: const InputDecoration(
labelText: "Kode Pola"),
onChanged: (value) {
setState(() {
_property1 = value;
});
},
),
const SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
myAlert();
},
child: Text('Upload Photo'),
),
SizedBox(
height: 10,
),
//if image not null show the image
//if image null show text
image != null
? Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
//to show image, you type like this.
File(image!.path),
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: 300,
),
),
)
: const Text(
"No Image",
style: TextStyle(fontSize: 20),
),
],
),
),
)
],
),
),
),
),
),
);
}
}
It also displays the error on Edge, but when I build the apk and run it on my physical device, it just shows nothing on the screen except for the data that's got above it. Any idea on how I can fix this?
var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
This returns a promise but not the actual data. In fact it could still be fetching the data when you attempt to convert it to a map.
You can await
var a = await FirebaseFirestore.instance.collection('PolaWillyJKT').get();
myDoc = a.docs.first();
Or use a callback that will run once the collection fetch completes:
FirebaseFirestore.instance.collection('PolaWillyJKT').get().then((response) => {
print(response);
});

how to copy a list of files after selecting multiple files inside listview.builder

i selected multiple files inside listview now i want to copy them. And then want to create input filed to make folder and zip files there.
List view builder
ListView.builder(
itemCount: files?.length ?? 0,
itemBuilder: (context, index) {
return InkWell(
onTap: () {},
child: Container(
child: MultiSelectItem(
isSelecting: myMultiSelectController.isSelecting,
onSelected: () {
setState(() {
myMultiSelectController.toggle(index);
});
},
child: Card(
color: myMultiSelectController.isSelected(index)
? Colors.blueAccent
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7)),
),
child: Center(
child: Text(files[index].path,
),
),
),
)
),
);
},
),
function to copy files
void copy() {
setState(() {
myMultiSelectController.set(files?.length ?? 0);
});
}
Solution ^^: get the selected files by using controller.isSelected inside the for loop
for(int i=0;i<multiSelectList.length;i++)
if(controller.isSelected(i)){
files.add(multiSelectList[i].path);
}
Example
class _MultiSelectListDemoState extends State<MultiSelectListDemo> {
List<FileModel> multiSelectList = [];
MultiSelectController controller = new MultiSelectController();
#override
void initState() {
super.initState();
multiSelectList.add(FileModel(path: 'assets/1.jpeg', name:"Welcome to New York City!"));
multiSelectList.add(FileModel(path: 'assets/2.jpeg', name:"Welcome to San francisco!"));
multiSelectList.add(FileModel(path: 'assets/3.jpeg', name:"Welcome to Chicago!"));
multiSelectList.add(FileModel(path: 'assets/4.jpeg', name:"Welcome to Houston!"));
controller.disableEditingWhenNoneSelected = true;
controller.set(multiSelectList.length);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
var before = !controller.isSelecting;
setState(() {
controller.deselectAll();
});
return before;
},
child: new Scaffold(
appBar: new AppBar(
title: new Text('Selected ${controller.selectedIndexes.length}' ),
),
body:Column(
children: [
Expanded(child: ListView.builder(
itemCount: multiSelectList.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {},
child: MultiSelectItem(
isSelecting: controller.isSelecting,
onSelected: () {
setState(() {
controller.toggle(index);
});
},
child:Container(
height:75,
margin: EdgeInsets.only(left:15,right:15,top:15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.transparent,
),
child:Card(
color:controller.isSelected(index)
? Colors.grey.shade200:Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
child:Padding(
padding:EdgeInsets.symmetric(vertical:10, horizontal: 12),
child: Row(
children: [
//contentPadding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
ClipRRect(
borderRadius: BorderRadius.circular(12),
child:Image.asset(multiSelectList[index].path,fit:BoxFit.cover,width:60,height:60,),
),
SizedBox(width:20,),
Text(multiSelectList[index].name, style: TextStyle(fontSize:14)),
],
),
),
),
),
),
);
},
)),
ElevatedButton(onPressed: (){
List<String> files = List.empty(growable: true);
for(int i=0;i<multiSelectList.length;i++)
if(controller.isSelected(i)){
files.add(multiSelectList[i].path);
}
print("selected files $files");
}, child: Text("zip"))
],
),
),
);
}
}
class FileModel{
final String path;
final String name;
FileModel({required this.path, required this.name});
#override
String toString() {
return 'FileModel{name: $name}';
}
}

Why is my Flutter PageView resetting when new any permission is selected by a user (iOS)

My app asks permission to access the photo library, camera, microphone, and location on the CreatePostScreen(). Whenever a user selects any option for those permission prompts, the PageView resets and goes to the first tab for some reason. None of the code in create_post_screen.dart calls for this and it only happens after permissions are set. I cannot figure out why this is happening.
create_post_screen.dart:
class CreatePostScreen extends StatefulWidget {
const CreatePostScreen({Key? key}) : super(key: key);
#override
State<CreatePostScreen> createState() => _CreatePostScreenState();
}
class _CreatePostScreenState extends State<CreatePostScreen> {
final _locationNameFormKey = GlobalKey<FormState>();
final _locationNameController = TextEditingController();
bool _isLoading = false;
List<String> originalFiles = [];
List<File> imageFiles = [];
void selectImages() async {
final result = await showModalActionSheet(
context: context,
title: 'Select Image Source',
actions: [
const SheetAction(label: 'Existing Images', key: 'existing'),
const SheetAction(label: 'New Image', key: 'new')
]);
if (result == 'new' && imageFiles.length < 4) {
newImage();
} else if (result == 'existing' && imageFiles.length < 4) {
existingImages();
}
}
void newImage() async {
setState(() {
_isLoading = true;
});
final XFile? image =
await ImagePicker().pickImage(source: ImageSource.camera);
if (image == null) return;
cropImages([image.path]);
}
void existingImages() async {
setState(() {
_isLoading = true;
});
final List<XFile>? selectedImages = await ImagePicker().pickMultiImage();
if (selectedImages == null) return;
int ableToAdd = 4 - imageFiles.length;
if (selectedImages.length > ableToAdd) {
List<XFile>? filesToAdd = selectedImages.sublist(0, ableToAdd);
List<String> imagePaths = [];
for (var selectedImage in filesToAdd) {
imagePaths.add(selectedImage.path);
}
cropImages(imagePaths);
} else {
List<String> imagePaths = [];
for (var selectedImage in selectedImages) {
imagePaths.add(selectedImage.path);
}
cropImages(imagePaths);
}
}
void cropImages(List<String> paths) async {
for (var path in paths) {
originalFiles.add(path);
final ImageProperties properties =
await FlutterNativeImage.getImageProperties(path);
final int width = properties.width!;
final int height = properties.height!;
int imageSize = width < height ? width : height;
int x = 0;
int y = 0;
File imageFile =
await FlutterNativeImage.cropImage(path, x, y, imageSize, imageSize);
setState(() {
int index = originalFiles.indexOf(path);
imageFiles.insert(index, imageFile);
_isLoading = false;
});
}
}
void customCrop(int index) async {
final fileToCrop = originalFiles[index];
final croppedFile = await ImageCropper().cropImage(
sourcePath: fileToCrop,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
aspectRatioPresets: [
CropAspectRatioPreset.square
],
uiSettings: [
AndroidUiSettings(toolbarTitle: 'Crop Image'),
IOSUiSettings(title: "Crop Image", showCancelConfirmationDialog: true)
]);
setState(() {
imageFiles[index] = File(croppedFile!.path);
});
}
Position? position;
void _determinePosition() async {
LocationPermission permission;
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
Position positionResult = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.lowest);
setState(() {
position = positionResult;
});
}
pkg.User user = Supabase.auth.currentUser!;
final postId = DateTime.now().millisecondsSinceEpoch.toString();
void uploadPost() async {
if (_locationNameFormKey.currentState!.validate()) {
_locationNameFormKey.currentState!.save();
setState(() {
_isLoading = true;
});
String name = _locationNameController.text;
Location location = Location(
position!.latitude,
position!.longitude,
name,
);
List<String> uploadedUrls = [];
for (var file in imageFiles) {
String fileName = '${DateTime.now().millisecondsSinceEpoch}_post.png';
Supabase.storage
.from('posts')
.upload('${user.id}/$fileName', supaFile.File(file.path));
String url = Supabase.storage.from('posts').getPublicUrl('${user.id}/$fileName');
setState(() {
uploadedUrls.add(url);
});
if (imageFiles.length == uploadedUrls.length) {
Post post = Post(
postId,
uploadedUrls,
user.id,
// profile,
location,
DateTime.now().millisecondsSinceEpoch,
);
print(post);
try {
Supabase.db
.from('posts')
.insert(post.toJson())
.then((value) {
setState(() {
imageFiles = [];
originalFiles = [];
_locationNameController.clear();
position = null;
_isLoading = false;
});
});
} catch (error) {
setState(() {
_isLoading = false;
});
print(error);
}
}
}
}
}
Widget imageItem(int index) {
File imageFile = imageFiles[index];
return SizedBox(
height: 200,
width: 200,
child: Card(
clipBehavior: Clip.hardEdge,
child: Stack(
children: [
Image.file(imageFile, fit: BoxFit.fill),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(5),
child: Row(
children: [
SizedBox(
height: 35,
width: 35,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
setState(() {
customCrop(index);
});
},
child: const Icon(Icons.edit_outlined),
),
),
),
const SizedBox(width: 5),
SizedBox(
height: 35,
width: 35,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
setState(() {
imageFiles.removeAt(index);
originalFiles.removeAt(index);
});
},
child: const Icon(Icons.delete_forever_sharp),
),
),
),
],
),
),
)
],
),
),
);
}
Widget picker() {
return imageFiles.isEmpty
? GestureDetector(
onTap: () {
selectImages();
},
child: Center(
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFd3d8e9),
borderRadius: BorderRadius.circular(10),
),
height: 150,
width: 300,
child: const Center(
child: Text(
'Press to add Images - Required',
style: TextStyle(color: Colors.red),
),
),
),
),
)
: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFd3d8e9),
borderRadius: BorderRadius.circular(10),
),
child: DragAndDropGridView(
physics: const ScrollPhysics(),
itemCount: imageFiles.length,
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (context, index) {
return imageItem(index);
},
onWillAccept: () {
return true;
},
onReorder: (oldIndex, newIndex) {
final temp = imageFiles[newIndex];
imageFiles[newIndex] = imageFiles[oldIndex];
imageFiles[oldIndex] = temp;
setState(() {});
},
),
),
),
],
);
}
#override
Widget build(BuildContext context) {
return Stack(
children: [
Scaffold(
resizeToAvoidBottomInset: true,
appBar: FloatingAppBar(
leading: const SizedBox(),
title: const Text('Create Post',
style: TextStyle(color: Color(0xFF7157A0), fontSize: 20)),
actions: [
if (imageFiles.isEmpty || position == null)
const Icon(Icons.send_outlined, color: Colors.grey),
if (imageFiles.isNotEmpty && position != null)
IconButton(
onPressed: () {
uploadPost();
},
icon:
const Icon(Icons.send_outlined, color: Color(0xFF7157A0)),
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
picker(),
Padding(
padding: const EdgeInsets.all(20),
child: Form(
key: _locationNameFormKey,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 80,
width: MediaQuery.of(context).size.width - 40,
child: TextFormField(
controller: _locationNameController,
textInputAction: TextInputAction.done,
keyboardType: TextInputType.name,
decoration: const InputDecoration(
suffix: Icon(Icons.edit_location_outlined,
color: Color(0xFF6C74B4)),
labelText: "Location Name",
floatingLabelStyle:
TextStyle(color: Color(0xFF697CB4)),
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(
color: Color(0xFF6B6FAB), width: 1)),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(
color: Color(0xFF697CB4), width: 1)),
),
validator: (name) {
if (name == null) {
return 'This cannot be left empty';
}
if (name.length < 4 || name.length > 15) {
return 'Must be 4-15 characters';
}
return null;
},
),
),
],
),
),
),
GestureDetector(
onTap: () {
_determinePosition();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
_determinePosition();
},
child: const Icon(Icons.location_on_outlined),
),
const SizedBox(width: 10),
if (position == null)
const Text(
'Press to add location - Required',
style: TextStyle(color: Colors.red),
),
if (position != null)
Text(
'Current location: ${position!.latitude.round()}, ${position!.longitude.round()}')
],
),
),
],
),
),
),
if (_isLoading)
const Opacity(
opacity: 0.8,
child: ModalBarrier(dismissible: false, color: Colors.black),
),
if (_isLoading)
const Center(
child: CircularProgressIndicator(color: Color(0xFFb1bbd8)),
),
],
);
}
}
I appreciate any help with this.

How to show images upon app start in flutter?

My app, when opened, doesn't show images stored on the Hive DB. After I upload a new one, it shows up and keeps showing fine.
If the app gets close, it won't show it again until it gets uploaded again
I tried to use listenable, and setStates(), and nothing worked, or I implemented it wrong.
import "dart:io";
import "package:flutter/material.dart";
import "package:flutter_speed_dial/flutter_speed_dial.dart";
import "package:hive_flutter/adapters.dart";
import "package:image_picker/image_picker.dart";
import "package:vortexcdl/model/incident_model.dart";
import "package:vortexcdl/widget/constants.dart";
import "../boxes.dart";
late Box boxImg;
class ImagesPage extends StatefulWidget {
ImagesPage({Key? key}) : super(key: key);
State<ImagesPage> createState() => _ImagesPageState();
}
class _ImagesPageState extends State<ImagesPage> {
//Variables
List? allImages = [];
List? pickedImages;
ImagesToSend imageObj = ImagesToSend();
///Get selection o fimages from Adnroid gallery
getImagesFromHive() async {
if (boxImg.containsKey("images_box")) {
// print(" BOX FOUND");
imageObj.images = await boxImg.getAt(0).images;
} else {
// print("Box does not exist...");
// imageObj.images = []; //Prevents null error;
}
}
Future pickImage(source) async {
final pickedImages = await source;
// print(pickedImages.length);
// print("%%%%%%%%%%%%%%%%");
if (pickedImages == null) return;
if (pickedImages is XFile) {
allImages!.add(pickedImages);
// print("############ Yes");
} else {
allImages!.addAll(pickedImages);
}
getImagesFromHive();
for (var i in allImages!)
imageObj.images.add(File(i.path).readAsBytesSync());
allImages = []; //Prevents deleted images to come back
boxImg.put("0", imageObj); //Save images in Hive
setState(() {});
}
//################### BUILD ##############################
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Images of the accident")),
body: _mainWidget(),
floatingActionButton: SpeedDial(
icon: Icons.collections,
backgroundColor: mainColor(),
children: [
SpeedDialChild(
child: Icon(
Icons.photo,
color: Colors.white,
),
backgroundColor: mainColor(),
label: "Gallery",
onTap: () async {
pickImage(ImagePicker().pickMultiImage());
},
),
SpeedDialChild(
child: Icon(
Icons.camera,
color: Colors.white,
),
backgroundColor: mainColor(),
label: "Camera",
onTap: () async {
pickImage(ImagePicker().pickImage(source: ImageSource.camera));
}),
],
),
);
}
Widget _mainWidget() {
return Column(children: [
ElevatedButton(
onPressed: () {
boxImg.clear();
setState(() {});
},
child: Text("Erase DB")),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: imageObj.images.length,
itemBuilder: (BuildContext context, int index) {
return generateGallery(index);
}))
]);
}
Widget generateGallery(index) {
getImagesFromHive();
return listenImages(Stack(
fit: StackFit.loose,
alignment: AlignmentDirectional.topEnd,
children: [
RawMaterialButton(
onPressed: () {},
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Image.memory(
imageObj.images[index],
width: 200,
height: 200,
fit: BoxFit.cover,
// child: Image.memory(
// boxImg.getAt(0).images[index],
// width: 200,
// height: 200,
// fit: BoxFit.cover,
))),
Padding(
padding: EdgeInsets.fromLTRB(0, 10, 10, 0),
child: ClipOval(
child: Container(
height: 40,
width: 40,
color: Colors.black.withAlpha(100),
child: IconButton(
onPressed: () {
setState(() {
imageObj.images.removeAt(index);
boxImg.put("0", imageObj);
});
},
icon: Icon(
Icons.close,
size: 20,
color: Colors.white,
)))))
]));
}
Widget listenImages(Widget w) {
return ValueListenableBuilder<Box<ImagesToSend>>(
valueListenable: BoxesImg.getImages().listenable(),
builder: (context, box, _) {
// print("####### LISTENING TO BOX IMAGES");
// setState(() {});
return w;
},
);
}
}
I tried multiple modifications and I was not able to solve this

Having issue with my favorite button functionality in flutter

I am having an issue with my favorite button. I have connected it with real-time firebase and each time I press the favorite icon it changes the state in firebase either true or false. when I press the heart button it always shows me different output sometimes it becomes red or black without affecting the other and sometimes it changes the other ones too (red or black). I have tried a lot to solve this but I am unable to get a solution for it.
class Home_page extends StatefulWidget {
#override
State<Home_page> createState() => _Home_pageState();
}
class _Home_pageState extends State<Home_page> {
//late StreamSubscription _dailySpecialStream;
var clr = Colors.grey;
//var item;
final List<String> _listItem = [
'assets/audi3.png',
'assets/audi.png',
'assets/audi2.png',
'assets/audi.png',
'assets/audi2.png',
'assets/audi3.png',
];
var name;
var auth1 = FirebaseAuth.instance.currentUser;
Data? c;
late final Value;
List<Data> dataList = [];
List<dynamic> d = [];
List<dynamic> favList = [];
#override
void initState() {
print("object");
super.initState();
print(auth1);
_activateListener();
}
void _activateListener() {
final _database = FirebaseDatabase.instance.ref();
_database.child('user').get().then((snapshot) {
dataList.clear();
favList.clear();
print("hello");
Value = snapshot.value as Map;
final datas = snapshot.children.forEach((element) {
d.add(element.key);
});
for (var k in d) {
//print("");
print(Value[k]['imgUrl']);
print((Value[k]['carName']).runtimeType);
dataList.add(Data(
Value[k]['carName'],
Value[k]['price'],
Value[k]["imgUrl"],
k,
));
if (auth1 != null) {
print(k);
print("auth1");
print(auth1);
DatabaseReference reference = FirebaseDatabase.instance
.ref()
.child("user")
.child(k)
.child("fav")
.child(auth1!.uid)
.child("state");
reference.get().then((s) {
print(s.value);
print("upp is vla");
if (s.value != null) {
if (s.value == true) {
// print(s.value);
// print("true");
favList.add(true);
print(favList);
} else {
//print(s.value);
print("false1");
favList.add(false);
//print(favList);
}
} else {
print("inelse");
favList.add(false);
print(favList);
}
});
}
}
Timer(Duration(seconds: 1), () {
setState(() {
inspect(favList);
});
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
color: Colors.white,
child: Stack(
children: [
Image.asset(
"assets/top.png",
fit: BoxFit.cover,
),
Column(
children: [
SizedBox(
height: 30,
),
search(context),
SizedBox(
height: 80,
),
Expanded(
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 40,
children: List.generate(
dataList.length, (index) => GridDesign(index)).toList(),
)),
],
)
],
),
),
),
);
}
SizedBox GridDesign(int index) {
return SizedBox(
child: Column(
children: [
Stack(
clipBehavior: Clip.none,
children: [
Container(
height: 15.h,
width: 45.w,
margin: EdgeInsets.only(left: 12, top: 12, right: 16),
decoration: BoxDecoration(
// border: Border.all(color: Colors.grey,style: BorderStyle.solid,width: 2),
borderRadius: BorderRadius.circular(5),
image: DecorationImage(
image: NetworkImage(dataList[index].url.toString()),
fit: BoxFit.cover)),
),
Positioned(
bottom: -3,
right: 5,
child: Container(
height: 32,
width: 32,
child: Neumorphic(
padding: EdgeInsets.zero,
style: NeumorphicStyle(
//shape: NeumorphicShape.concave,
boxShape: NeumorphicBoxShape.roundRect(
BorderRadius.circular(50)),
color: Colors.white),
child: favList[index]
? IconButton(
padding: EdgeInsets.zero,
onPressed: () {
if (auth1 != null) {
print(auth1);
print("it's not null");
DatabaseReference favRef = FirebaseDatabase
.instance
.ref()
.child("user")
.child(
dataList[index].uploadId.toString())
.child("fav")
.child(auth1!.uid)
.child("state");
favRef.set(false);
setState(() {
favFun();
});
}
print("object");
},
icon: Icon(
Icons.favorite,
color: Colors.red,
),
)
: IconButton(
padding: EdgeInsets.zero,
onPressed: () {
if (auth1 != null) {
print("it's not null1");
print(auth1);
DatabaseReference favRef = FirebaseDatabase
.instance
.ref()
.child("user")
.child(
dataList[index].uploadId.toString())
.child("fav")
.child(auth1!.uid)
.child("state");
favRef.set(true);
setState(() {
favFun();
});
}
print("object");
},
icon: Icon(
Icons.favorite,
))),
),
),
],
),
SizedBox(
height: 4,
),
Expanded(child: Text(dataList[index].CarName.toString())),
SizedBox(height: 2),
Expanded(
child: Text("R" + dataList[index].price.toString()),
),
SizedBox(height: 3),
Expanded(
child: ElevatedButton(
onPressed: () =>
Get.to(DetailPage(dataList[index].Url, dataList[index].Price)),
child: Text("Details"),
style: ElevatedButton.styleFrom(primary: myColor),
))
],
),
);
}
void favFun() {
final _database = FirebaseDatabase.instance.ref();
_database.child('user').get().then((snapshot) {
favList.clear();
for (var k in d) {
//print("");
if (auth1 != null) {
print(k);
print("auth1");
print(auth1);
DatabaseReference reference = FirebaseDatabase.instance
.ref()
.child("user")
.child(k)
.child("fav")
.child(auth1!.uid)
.child("state");
reference.once().then((DatabaseEvent s) {
print(s.snapshot.value);
print("upp is vla");
if (s.snapshot.value != null) {
if (s.snapshot.value == true) {
// print(s.value);
// print("true");
favList.add(true);
print(favList);
} else {
//print(s.value);
print("false1");
favList.add(false);
//print(favList);
}
} else {
print("inelse");
favList.add(false);
print(favList);
}
});
}
}
Timer(Duration(seconds: 1), () {
setState(() {
//inspect(favList);
});
});
});
}
}
Have a look at the picture to get a better view