Skip to content

Instantly share code, notes, and snippets.

@Sofianel5
Created March 5, 2021 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sofianel5/3b29e15024b902f6f04ce2f84598171c to your computer and use it in GitHub Desktop.
Save Sofianel5/3b29e15024b902f6f04ce2f84598171c to your computer and use it in GitHub Desktop.
Flutter NetworkImage memory issue
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Memory Issue',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Flutter Demo Home Page',
imageUrl: "https://picsum.photos/",
),
);
}
}
class GalleryImage extends StatelessWidget {
final String url;
final int height;
final int width;
GalleryImage(this.url, this.height, this.width);
@override
Widget build(BuildContext context) {
return Container(
width: (MediaQuery.of(context).size.width / 3),
height: height * (MediaQuery.of(context).size.width / 3) / width,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
url,
),
fit: BoxFit.cover,
),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage(
{Key key, this.title, this.imageUrl})
: super(key: key);
final String imageUrl;
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static var _random = new Random();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: CustomScrollView(
slivers: <Widget>[
SliverStaggeredGrid.countBuilder(
crossAxisCount: 3,
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
int width = 100 + _random.nextInt(1800);
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => MyHomePage(
title: 'Flutter Demo Home Page',
imageUrl: widget.imageUrl,
)));
},
child: GalleryImage(widget.imageUrl + width.toString(), width,
width),
);
},
staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
mainAxisSpacing: 0,
crossAxisSpacing: 0,
),
],
),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment