wingchun
wingchun

Reputation: 11

How to prevent the CustomPainter::paint() function from being called when the state of Scaffold::appBar changes

When the state of a button in the Scaffold::appBar changes, the CustomPainter::paint() added to the ::body is automatically called.

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class PageTest extends StatefulWidget {
  const PageTest({Key? key}) : super(key: key);

  @override
  PageTestState createState() => PageTestState();
}

class PageTestState extends State<PageTest> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text('Page Test'),
        titleTextStyle: const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.radio_button_checked, color: Colors.redAccent),
            onPressed: () {},
          ),
        ],
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return Center(
      child: CustomPaint(
        painter: PageTestPaint(),
      ),
    );
  }
}

class PageTestPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    double size = 200.0;
    double sizeHalf = size * 0.5;

    /// draw box
    canvas.drawRect(
      Rect.fromLTWH(-sizeHalf, -sizeHalf, size, size),
      Paint()..color = Colors.lightBlue,
    );

    /// text setting
    const fontSize = 12.0;
    String text = DateTime.now().toString();
    final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle(fontSize: fontSize, textAlign: TextAlign.center))
      ..pushStyle(ui.TextStyle(color: Colors.black, fontWeight: FontWeight.bold))
      ..addText(text);
    ui.Paragraph paragraph = paragraphBuilder.build()..layout(ui.ParagraphConstraints(width: size));

    /// draw text
    canvas.drawParagraph(
      paragraph,
      Offset(-sizeHalf, 0),
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

I want to make sure that if the content of the ::appBar changes, the CustomPainter::paint() added to the ::body is not re-rendered.

Is there a way to do this?

Upvotes: 1

Views: 85

Answers (0)

Related Questions