Creare un custom painter in Flutter

Mattepuffo's logo
Creare un custom painter in Flutter

Creare un custom painter in Flutter

Attraverso la classe CustomPainter possiamo facilmente creare un custom painter in Flutter.

In questo articolo vediamo coome crearne uno.

Cominciamo proprio dalla nostra classe:

import 'package:flutter/material.dart';

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.amber
      ..strokeWidth = 5.0
      ..style = PaintingStyle.fill;

    Rect rect = const Rect.fromLTWH(50, 50, 100, 100);
    canvas.drawRect(rect, paint);

    Offset offset = Offset(size.width / 2, size.height / 2);
    canvas.drawCircle(offset, 50, paint);
  }

  @override
  bool shouldRepaint(CustomPainter delegate) {
    return false;
  }
}

Per usarlo;

import 'package:flutter/material.dart';

import 'custom_painter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Test',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Flutter Test'),
      ),
      body: Center(
        child: CustomPaint(
          painter: MyPainter(),
        ),
      ),
    );
  }
}

Enjoy!


Condividi

Commentami!