Reputation: 202
I have a ListView.builder
that builds a list of random images from PicsumPhotos.
Everything works as expected, expect for a strange behaviour with scroll. Once the list is fully rendered, if I scroll up or scroll down, the itemBuilder
function fires once (once for scroll up, and once for scroll down), causing fetching a new first image (when scroll up) and a new last image (when scroll down).
I'm missing something? Thanks in advance.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:components_demo/shared/components/appbar_back.dart';
class ListViewPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ListViewPageState();
}
class _ListViewPageState extends State<ListViewPage> {
int itemCount = 0;
@override
void initState() {
super.initState();
_setItemCount();
}
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBarBack('ListView'), body: _createList());
}
Widget _createList() {
final random = Random();
return ListView.builder(
key: Key('myList'),
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) { // when scroll up/down, fires once
final photoIndex = random.nextInt(250);
print(photoIndex);
return FadeInImage(
image: Image.network('https://picsum.photos/id/$photoIndex/500/300').image,
placeholder: Image.asset('assets/jar-loading.gif').image,
);
},
);
}
void _setItemCount() {
setState(() {
itemCount = 5;
});
}
}
Upvotes: 0
Views: 590
Reputation: 884
Give your image a UniqueKey
. The item builder doesn’t know it’s the same widget because it can’t identify it.
FadeInImage(
key: UniqueKey(),
),
Upvotes: 1