我以为当我悬停在 FAB 上时,只有 FAB 会发生变化,其他一切都会保持不变,但是当我悬停在 FAB 上时,CustomPaint 小部件正在重新绘制。我想知道为什么会这样,因为我认为 CustomPaint 只是在我按下 FAB 时才重新绘制。
class HomePage extends HookWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final toggle = useState(false);
debugPrint('HomePage rebuild');
return Scaffold(
body: Center(
child: Container(
height: 250,
width: 250,
child: CustomPaint(
painter: PanelBackend(Colors.red, toggle),
foregroundPainter:
PanelFrontend(Colors.blue.withOpacity(1), toggle),
child: Container(
height: 100.0,
width: 100.0,
color: Colors.transparent,
child: const Text('Middle'),
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => toggle.value = !toggle.value,
child: const Icon(Icons.add),
),
);
}
}
class PanelBackend extends CustomPainter {
final Color color;
final ValueNotifier<bool> notifier;
PanelBackend(this.color, this.notifier) : super(repaint: notifier);
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = color;
final stamp = DateTime.now().millisecondsSinceEpoch;
debugPrint('$stamp : Backend painted, size: ${size.toString()}');
canvas.drawRect(
Rect.fromPoints(Offset.zero, Offset(size.width, size.height)), paint);
}
@override
bool shouldRepaint(covariant PanelBackend oldDelegate) {
return notifier.value != oldDelegate.notifier.value;
}
}
class PanelFrontend extends CustomPainter {
final Color color;
final ValueNotifier<bool> notifier;
PanelFrontend(this.color, this.notifier) : super(repaint: notifier);
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = color;
final stamp = DateTime.now().millisecondsSinceEpoch;
debugPrint('$stamp : Front painted, size: ${size.toString()}');
canvas.drawRect(
Rect.fromPoints(Offset.zero, Offset(size.width, size.height)), paint);
}
@override
bool shouldRepaint(covariant PanelFrontend oldDelegate) {
return notifier.value != oldDelegate.notifier.value;
}
}
我尝试使用 ElevatedButton 而不是 FAB,但结果相同,即悬停时,CustomPaint 已重建。
然而,我尝试使用 GestureDetector 而不是 FAB 或 ElevatedButton,然后它就像我想象的那样。