I made vertical scroll list of question cards with selected pictures at the end of list using image_picker
with scroll_to_index
. I can see pictures right after I picked the pictures but when I scroll up the list, the selected pictures keep disappearing. It seems like the imageList
in child widget does not maintain changed values of list. here is my short code.
parent.dart
class Parent extends StatefulWidget {
const Parent({Key? key}) : super(key: key);
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
@override
Widget build(BuildContext context) {
return Scaffold(body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: ListView.builder(
padding: EdgeInsets.all(8),
itemCount: _list.length + 1,
itemBuilder: ((context, index) {
if (index != _list.length) {
return AutoScrollTag( //scroll_to_index
key: ValueKey(index), //scroll_to_index
controller: scrollController, //scroll_to_index
index: index,
highlightColor: Colors.blue.withOpacity(0.3),
child: Container(
...
}else(){
return Child();
}
));
}
}
child.dart
class Child extends StatefulWidget {
const Child({Key? key}) : super(key: key);
@override
State<Child> createState() => _ChildState();
}
class _ChildState extends State<Child> {
List<String> imageList = [];
pickMultiImages() async {
final List<PickedFile>? selectedImages =
await ImagePicker.platform.pickMultiImage();
if (selectedImages != null) {
imageList.addAll(selectedImages);
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Wrap(
children: [
if (imageList.length > 0)
for (int i = 0; i < imageList.length; i++)
Stack(children: [
Column(
...
,
IconButton(onPressed: (() => {
pickMultiImages()
}), icon: Icon(Icons.add))
],
);
this code does not work.
but When I added List<PickedFile> imageList = []
and pass to child widget as parameter in Parent Widget and in Child Widget,
class Child extends StatefulWidget {
List<PickedFile> imageList = []; // added
Child({
Key? key,
required this.imageList, // added
}) : super(key: key);
...
pickMultiImages() async {
...
widget.imageList.addAll(selectedImages); // imageList.addAll -> widget.imageList.addAll
...
setState(() {});
}
this one worked. Should I always declare the changing child state in parent widget? or this is just special case that i have to do like this?