I am trying to fetch lots of images from firebase storage and display it in my flutter app but I am facing speed issues. It is taking a lot of time for the images to load. Also once the images are loaded they are loading again after I scroll down and scroll up. Is there any solution to this ?. This is my code.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: WallpaperScreen(),
);
}
}
class WallpaperScreen extends StatefulWidget {
@override
_WallpaperScreenState createState() => _WallpaperScreenState();
}
class _WallpaperScreenState extends State<WallpaperScreen> {
List<String> imageUrls = [];
@override
void initState() {
super.initState();
fetchImages();
}
Future<void> fetchImages() async {
try {
final storageRef = FirebaseStorage.instance
.refFromURL("firebase url");
final result = await storageRef.listAll();
for (var item in result.items) {
try {
final url = await item.getDownloadURL();
setState(() {
imageUrls.add(url);
});
} catch (error) {
print("Error fetching URL: $error");
}
}
} catch (e) {
print("Error fetching images: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xff0e0023),
Color(0xff3a1e54),
],
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 40),
const Align(
alignment: Alignment.topCenter,
child: Text(
'Wallpapers',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: GridView.builder(
itemCount: imageUrls.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 9 / 16,
crossAxisSpacing: 30,
mainAxisSpacing: 30,
),
itemBuilder: (BuildContext context, int index) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullScreenImageScreen(
imageUrl: imageUrls[index],
),
),
);
},
child: Image.network(
imageUrls[index],
fit: BoxFit.cover,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child;
} else {
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes !=
null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
}
},
),
),
);
},
),
),
),
],
),
),
);
}
}