Created
November 4, 2020 00:36
-
-
Save liyuqian/a2214c60c3539fd5fab4b53f24b75203 to your computer and use it in GitHub Desktop.
Demo Flutter app to show how one can blow up memory by having many picture raster caches.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(CacheMemTestApp()); | |
} | |
class CacheMemTestApp extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() { | |
return CacheMemTestAppState(); | |
} | |
} | |
class CacheMemTestAppState extends State<CacheMemTestApp> { | |
static const int kMaxCount = 20; | |
int count = 1; | |
@override | |
Widget build(BuildContext context) { | |
final List<Color> colors = [Colors.red, Colors.green, Colors.blue]; | |
final List<CacheBlock> blocks = []; | |
for (int i = 0; i < count; i += 1) { | |
blocks.add(CacheBlock( | |
colors[i % colors.length], | |
Offset(i * 10.0, i * 10.0), | |
)); | |
} | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: Scaffold( | |
body: Center( | |
child: ListView( | |
children: [ | |
Stack( | |
children: blocks, | |
) | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
count += 1; | |
count -= count > kMaxCount ? kMaxCount : 0; | |
}); | |
}, | |
child: Text('+'), | |
), | |
), | |
); | |
} | |
} | |
class CacheBlock extends StatelessWidget { | |
CacheBlock(this.color, this.offset); | |
final Color color; | |
final Offset offset; | |
@override | |
Widget build(BuildContext context) { | |
return Transform.translate( | |
offset: offset, | |
child: RepaintBoundary( | |
child: CustomPaint( | |
painter: CacheBlockPainter(color), | |
isComplex: true, | |
willChange: false, | |
child: Container( | |
width: 2000, | |
height: 2000, | |
), | |
), | |
), | |
); | |
} | |
} | |
class CacheBlockPainter extends CustomPainter { | |
CacheBlockPainter(this.color); | |
final Color color; | |
@override | |
void paint(Canvas canvas, Size size) { | |
canvas.drawRect(Offset.zero & size, Paint()..color = color.withOpacity(0.5)); | |
} | |
@override | |
bool shouldRepaint(covariant CustomPainter oldDelegate) => true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment