Flutter: CustomPainter paint method gets called several times instead of only once - flutter

I have a simple app that draws via a CustomPainter a red or green circle on a canvas, depending on which button is pressed in the AppBar:
The class ColorCircle extends CustomPainter and is responsible for drawing the colored circle:
class ColorCircle extends CustomPainter {
MaterialColor myColor;
ColorCircle({#required this.myColor});
#override
void paint(Canvas canvas, Size size) {
debugPrint('ColorCircle.paint, ${DateTime.now()}');
final paint = Paint()..color = myColor;
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 100, paint);
}
#override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
The drawing of the different colors works fine, but when I click (only once!) or hover over one of the buttons, the paint method gets called several times:
Further implementation details:
I use a StatefulWidget for storing the actualColor. In the build method actualColor is passed to the ColorCircle constructor:
class _MyHomePageState extends State<MyHomePage> {
MaterialColor actualColor = Colors.red;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
OutlinedButton(
onPressed: () => setState(() => actualColor = Colors.red),
child: Text('RedCircle'),
),
OutlinedButton(
onPressed: () => setState(() => actualColor = Colors.green),
child: Text('GreenCircle'),
),
],
),
body: Center(
child: CustomPaint(
size: Size(300, 300),
painter: ColorCircle(myColor: actualColor),
),
),
);
}
}
The complete source code with a running example can be found here: CustonPainter Demo
So why is paint called several times instead of only once? (And how could you implement it so that paint is called only once?).

All you need to do is to warp the CustomPaint with RepaintBoundary
Center(
child: RepaintBoundary(
child: CustomPaint(
size: Size(300, 300),
painter: ColorCircle(myColor: actualColor),
),
),
By default CustomPainter is in the same layer as every other widget on the same screen so it's paint method will get called if any other widget on the same screen repaint.
To fix this we can isolate the CustomPainter with RepaintBoundary so any repainting outside this RepaintBoundary wont effect it, or we can fix it by warping other widgets that would repaint with RepaintBoundary so they won't effect any other widgets (including the CustomPainter widget) when they get repaint, however it's better to just warp the CustomPainter with the RepaintBoundary instead of warping multiple widgets with RepaintBoundary since it's costly and sometimes have no effect.
You can get a better view and understanding of this by enabling Highlight repaints in the DevTools.

A poor solution might be to add a RepaintBoundary around the hover Widgets:
class _MyHomePageState extends State<MyHomePage> {
MaterialColor actualColor = Colors.red;
#override
Widget build(BuildContext context) {
print('Rebuilding with $actualColor');
return Scaffold(
appBar: AppBar(
title: Text('CustomPainter Demo'),
actions: <Widget>[
RepaintBoundary(
child: OutlinedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {
setState(() => actualColor = Colors.red);
},
child: Text('RedCircle')),
),
RepaintBoundary(
child: OutlinedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {
setState(() => actualColor = Colors.green);
},
child: Text('GreenCircle')),
),
],
),
body: Center(
child: CustomPaint(
size: Size(300, 300),
painter: ColorCircle(myColor: actualColor),
),
),
);
}
}
And then, to properly define the shouldRepaint method of the ColorCircle (currently returning false):
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return (oldDelegate as ColorCircle).myColor != myColor;
}
This seems to be a really poor solution. I would be interested to know of a better, more sustainable answer.
Full source code with RepaintBoundary workaround
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'CustomPainter Demo',
home: MyHomePage(),
);
}
}
class ColorCirle extends CustomPainter {
MaterialColor myColor;
ColorCirle({#required this.myColor});
#override
void paint(Canvas canvas, Size size) {
debugPrint('ColorCircle.paint, ${DateTime.now()}');
final paint = Paint()..color = myColor;
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 100, paint);
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return (oldDelegate as ColorCirle).myColor != myColor;
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MaterialColor actualColor = Colors.red;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CustomPainter Demo'),
actions: <Widget>[
RepaintBoundary(
child: OutlinedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {
setState(() => actualColor = Colors.red);
},
child: Text('RedCircle')),
),
RepaintBoundary(
child: OutlinedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all(Colors.black)),
onPressed: () {
setState(() => actualColor = Colors.green);
},
child: Text('GreenCircle')),
),
],
),
body: Center(
child: CustomPaint(
size: Size(300, 300),
painter: ColorCirle(myColor: actualColor),
),
),
);
}
}

Related

CustomPainter's paint method is not getting called before WidgetsBinding.instance.addPostFrameCallback in case of Multiple navigation

I have a Flutter StatefulWidget and in initState() method I am using WidgetsBinding.instance.addPostFrameCallback to use one instance variable (late List _tracks). like -
WidgetsBinding.instance.addPostFrameCallback((_) {
for(itr = 0; itr<_tracks.length; itr++){
// some logic
}
});
As this would get invoked after all Widgets are done. In one of the CustomPaint's painter class I am initializing that variable.
SizedBox.expand(
child: CustomPaint(
painter: TrackPainter(
trackCalculationListener: (tracks) {
_tracks = tracks;
}),
),
),
It is working fine when I have one screen, i.e the same class. But, When I am adding one screen before that and trying to navigate to this screen from the new screen it is throwing _tracks is not initialized exception.
new screen is very basic -
class MainMenu extends StatefulWidget {
const MainMenu({super.key});
#override
State<MainMenu> createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.white,
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Play(),
maintainState: false));
},
child: const Text('play game'),
),
),
);
}
}
In single screen case the paint method of painter is getting called before postFrameCallback but in case of multiple it is not getting before postFrameCallback and because of that the variable is not getting initialized.
reproducible code -
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/mainMenu': (context) => const MainMenu(),
'/game': (context) => const MyHomePage(title: 'game'),
},
initialRoute: '/mainMenu',
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<Rect> _playerTracks;
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
print(_playerTracks.length);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
color: Colors.white,
margin: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: 1,
child: SizedBox.expand(
child: CustomPaint(
painter: RectanglePainter(
trackCalculationListener: (playerTracks) =>
_playerTracks = playerTracks),
),
),
),
)
],
),
),
);
}
}
class MainMenu extends StatefulWidget {
static String route = '/mainMenu';
const MainMenu({super.key});
#override
State<MainMenu> createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 200.0,
color: Colors.white,
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/game');
},
child: const Text('play game'),
),
),
),
);
}
}
class RectanglePainter extends CustomPainter {
Function(List<Rect>) trackCalculationListener;
RectanglePainter({required this.trackCalculationListener});
#override
void paint(Canvas canvas, Size size) {
final Rect rect = Offset.zero & size;
const RadialGradient gradient = RadialGradient(
center: Alignment(0.7, -0.6),
radius: 0.2,
colors: <Color>[Color(0xFFFFFF00), Color(0xFF0099FF)],
stops: <double>[0.4, 1.0],
);
canvas.drawRect(
rect,
Paint()..shader = gradient.createShader(rect),
);
List<Rect> _playerTracks = [];
_playerTracks.add(rect);
trackCalculationListener(_playerTracks);
}
#override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
I am very new to flutter and would highly appreciate if someone could help me figure out what I am doing wrong here.

CustomPainter together with Paint()..blendMode gives weird blinking effect while scrolling

After launching the application, the green circle is not visible. In order for the circle to appear, you need to scroll up. Then if you scroll down, the circle starts blinking as long as the scrolloffset is within about 20 pixels. If the scrolloffset is larger than 20 pixels, the circle disappears and appears only when the scrolloffset is 0.
If wrap the widget in RepaintBoundary, then the circle appears on any scroll and then does not disappear.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class DemoPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) {
canvas.save();
final path = Path()..addOval(Rect.fromCircle(center: Offset.zero, radius: 50));
final paint = Paint()..color = Colors.green;
paint.blendMode = BlendMode.dstOver;
canvas.drawPath(path, paint);
canvas.restore();
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
class TestWidget extends StatelessWidget {
const TestWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SizedBox(
height: 80,
child: Center(
child: CustomPaint(
painter: DemoPainter(),
child: Text(
"Child widget",
style: TextStyle(color: Colors.blue[200], fontWeight: FontWeight.bold, fontSize: 20),
),
),
));
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
home: Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
const TestWidget(),
const TestWidget(),
const TestWidget(),
const TestWidget(),
const RepaintBoundary(child: TestWidget()),
Container(
height: 2000,
color: Colors.red,
)
],
),
),
),
);
}
}
The link to Dartpad, but i can't reproduce the effect on the web platform.
What could be the reason for such effect and how to get rid of it?

Flutter - Animate a widget to move from GridView to BottomBar upon tapping

I am looking to animate an image widget to move from a grid view to the bottom bar as shown below but much simpler. Could anyone provide me any guidance as to how to achieve this? I am leaning towards a transform animation, but I have hit a wall trying to calculate the source and destination screen points. Any help is highly appreciated.
Try this package, add_cart_parabola:
import 'dart:ui';
import 'package:add_cart_parabola/add_cart_parabola.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
GlobalKey floatKey = GlobalKey();
GlobalKey rootKey = GlobalKey();
Offset floatOffset ;
#override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
RenderBox renderBox = floatKey.currentContext.findRenderObject();
floatOffset = renderBox.localToGlobal(Offset.zero);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
key: rootKey,
width: double.infinity,
height: double.infinity,
color: Colors.grey,
child: ListView(
children: List.generate(40, (index){
return generateItem(index);
}).toList(),
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.yellow,
key: floatKey,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget generateItem(int index){
Text text = Text("item $index",style: TextStyle(fontSize:
25),);
Offset temp;
return GestureDetector(
onPanDown: (details){
temp = new Offset(details.globalPosition.dx, details.globalPosition
.dy);
},
onTap: (){
Function callback ;
setState(() {
OverlayEntry entry = OverlayEntry(
builder: (ctx){
return ParabolaAnimateWidget(rootKey,temp,floatOffset,
Icon(Icons.cancel,color: Colors.greenAccent,),callback,);
}
);
callback = (status){
if(status == AnimationStatus.completed){
entry?.remove();
}
};
Overlay.of(rootKey.currentContext).insert(entry);
});
},
child: Container(
color: Colors.orange,
child: text,
),
);
}
}

Flutter PopupMenuButton onLongPressed

I'm trying to show a menu context on a custom widget I created when it is long pressed(on tap has another behaviour).
I tried to use GestureDetector with onLongPress and use the function showMenu but it shows the menu in the corner, not over the widget pressed. I've seen a workaround to get the position of the widget and pass it to the showMenu but it looks messy to me.
return new GestureDetector(
child: _defaultBuild(),
onTap: onTap,
onLongPress: () {
showMenu(
items: <PopupMenuEntry>[
PopupMenuItem(
//value: this._index,
child: Row(
children: <Widget>[
Text("Context item1")
],
),
)
],
context: context,
position: _getPosition(context)
);
}
);
RelativeRect _getPosition(BuildContext context) {
final RenderBox bar = context.findRenderObject();
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
),
Offset.zero & overlay.size,
);
return position;
}
I've tried also to use PopupMenuButton but I wasn't able to show the menu onLongPressed.
Any ideas?
showMenu() works well on my end. It looks like the issue has something to do with how the menu is being positioned with RelativeRect. Instead of RelativeRect.fromRect(), I used RelativeRect.fromSize() on mine.
RelativeRect _getRelativeRect(GlobalKey key){
return RelativeRect.fromSize(
_getWidgetGlobalRect(key), const Size(200, 200));
}
Rect _getWidgetGlobalRect(GlobalKey key) {
final RenderBox renderBox =
key.currentContext!.findRenderObject() as RenderBox;
var offset = renderBox.localToGlobal(Offset.zero);
debugPrint('Widget position: ${offset.dx} ${offset.dy}');
return Rect.fromLTWH(offset.dx / 3.1, offset.dy * 1.05,
renderBox.size.width, renderBox.size.height);
}
Here's a complete sample that you can try.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final widgetKey = GlobalKey();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: GestureDetector(
key: widgetKey,
child: Container(
height: 60,
width: 120,
color: Colors.lightBlueAccent,
child: const Center(child: Text('Show Menu')),
),
onLongPress: () {
showMenu(
items: <PopupMenuEntry>[
PopupMenuItem(
//value: this._index,
child: Row(
children: const [Text("Context item 1")],
),
)
],
context: context,
position: _getRelativeRect(widgetKey),
);
},
),
),
);
}
RelativeRect _getRelativeRect(GlobalKey key){
return RelativeRect.fromSize(
_getWidgetGlobalRect(key), const Size(200, 200));
}
Rect _getWidgetGlobalRect(GlobalKey key) {
final RenderBox renderBox =
key.currentContext!.findRenderObject() as RenderBox;
var offset = renderBox.localToGlobal(Offset.zero);
debugPrint('Widget position: ${offset.dx} ${offset.dy}');
return Rect.fromLTWH(offset.dx / 3.1, offset.dy * 1.05,
renderBox.size.width, renderBox.size.height);
}
}

Flutter: Update state of sibling widget

How do you update the state of a sibling widget in Flutter?
For example, if I have a rectangle widget, I can change its color from within the widget by calling setState() and changing the color variable (as the "Turn Green" button does below). But, say I wanted a button outside of the rectangle that would change its color. How do I communicate to the Rectangle that it's time to change its color, and what color to change to?
Here is my sample code. When the user presses the "Turn Blue" button, I'd like the rectangle to turn blue, but I don't have access to its state from the sibling widget.
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: Column(
children: <Widget>[
HelloRectangle(),
FlatButton(
child: Text('Turn Blue!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// How to update state of the Rectangle from here?
},
),
]
),
),
),
);
}
class HelloRectangle extends StatefulWidget {
#override
HelloRectangleState createState() {
return new HelloRectangleState();
}
}
class HelloRectangleState extends State<HelloRectangle> {
Color _color;
#override
void initState() {
super.initState();
_color = Colors.red;
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: _color,
height: 400.0,
width: 300.0,
child: Center(
child: FlatButton(
child: Text('Turn Green!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// I can update the state from here because I'm inside the widget
setState(() {
_color = Colors.green;
});
},
),
),
),
);
}
}
The rule of thumb is that you can't access the state of any Widget that isn't above you in the hierarchy. So, basically we need to move the state (color) up to an ancestor. Introduce a StatefulWidget that builds the Scaffold or Column and store the rectangle color there. Now the rectangle widget no longer needs to store the color, so can become a stateless widget - and you can pass the color in through the constructor. Both onPressed callbacks can now call a method on the new StatefulWidget which calls setState. (You could pass that method down to the rectangle widget, amongst other ways.)
There are two good introductions to best practise here and here.
Here is basic example how to do it from outside.
import 'package:flutter/material.dart';
void main() {
runApp(
new MyApp(),
);
}
class MyApp extends StatefulWidget {
const MyApp({
Key key,
}) : super(key: key);
#override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
MaterialColor _color = Colors.green;
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: Column(children: <Widget>[
HelloRectangle(_color),
FlatButton(
child: Text(
_color == Colors.green ? "Turn Blue" : "Turn Green",
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
setState(() {
_color = _color == Colors.green ? Colors.blue : Colors.green;
});
},
),
]),
),
);
}
}
class HelloRectangle extends StatefulWidget {
final Color color;
HelloRectangle(this.color);
#override
HelloRectangleState createState() {
return new HelloRectangleState();
}
}
class HelloRectangleState extends State<HelloRectangle> {
HelloRectangleState();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: widget.color,
height: 400.0,
width: 300.0,
),
);
}
}