Created
January 7, 2023 15:10
-
-
Save g123k/3dec9ab3a3cdaac12856afa170be5bc8 to your computer and use it in GitHub Desktop.
Exemple de Widget consommant beaucoup de ressources
This file contains 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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
class ExpensiveWidget extends StatefulWidget { | |
const ExpensiveWidget({super.key}); | |
@override | |
State<StatefulWidget> createState() => ExpensiveWidgetState(); | |
} | |
class ExpensiveWidgetState extends State<ExpensiveWidget> { | |
final GlobalKey _paintKey = GlobalKey(); | |
Offset _offset = Offset.zero; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Stack( | |
fit: StackFit.expand, | |
children: <Widget>[ | |
RepaintBoundary( | |
child: CustomPaint( | |
painter: _ExpensivePainter(), | |
isComplex: false, | |
willChange: true, | |
), | |
), | |
Listener( | |
onPointerDown: _updateOffset, | |
onPointerMove: _updateOffset, | |
child: CustomPaint( | |
key: _paintKey, | |
painter: MyCustomPainter(_offset), | |
child: const SizedBox.expand(), | |
), | |
), | |
], | |
), | |
); | |
} | |
_updateOffset(PointerEvent event) { | |
RenderBox? referenceBox = | |
_paintKey.currentContext?.findRenderObject() as RenderBox?; | |
Offset? offset = referenceBox?.globalToLocal(event.position); | |
if (offset != null) { | |
setState(() => _offset = offset); | |
} | |
} | |
} | |
class _ExpensivePainter extends CustomPainter { | |
final Random rand = Random(12345); | |
final List<Color> colors = [ | |
Colors.red, | |
Colors.blue, | |
Colors.yellow, | |
Colors.green, | |
Colors.white, | |
]; | |
@override | |
void paint(Canvas canvas, Size size) { | |
print("Paint rainbow"); | |
for (int i = 0; i < 100000; i++) { | |
canvas.drawCircle( | |
Offset(rand.nextDouble() * size.width, rand.nextDouble() * size.height), | |
10 + rand.nextDouble() * 20, | |
Paint()..color = colors[rand.nextInt(colors.length)].withOpacity(0.2), | |
); | |
} | |
} | |
@override | |
bool shouldRepaint(_ExpensivePainter oldDelegate) => false; | |
} | |
class MyCustomPainter extends CustomPainter { | |
MyCustomPainter(this._offset); | |
final Offset _offset; | |
final Paint _paint = Paint()..color = Colors.black; | |
@override | |
void paint(Canvas canvas, Size size) { | |
print("Paint cursor"); | |
canvas.drawCircle(_offset, 10.0, _paint); | |
} | |
@override | |
bool shouldRepaint(MyCustomPainter oldDelegate) => | |
oldDelegate._offset != _offset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment