Last active
March 20, 2024 12:27
-
-
Save canalun/ba7f3bad609979f35586a3ef16d71c8b to your computer and use it in GitHub Desktop.
a11y in flutter canvas
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
// The implementation is based on https://developers.cyberagent.co.jp/blog/archives/36573/ | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/rendering.dart'; | |
void main() { | |
WidgetsFlutterBinding.ensureInitialized(); | |
// Auto-enable accessibility for our Blind and Low Vision customers. | |
// RendererBinding.instance.accessibilityFeatures | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const CustomPaint( | |
painter: _HelloTextPainter(), | |
); | |
} | |
} | |
class _HelloTextPainter extends CustomPainter { | |
const _HelloTextPainter(); | |
static const _horizontalMargin = 16.0; | |
@override | |
void paint(Canvas canvas, Size size) { | |
final paint = Paint()..color = Colors.red; | |
final text = TextPainter( | |
textDirection: TextDirection.ltr, | |
text: const TextSpan( | |
style: TextStyle( | |
color: Colors.white, | |
), | |
text: 'Hello', | |
), | |
)..layout(); | |
// [canvas] に赤い長方形を描画 | |
canvas.drawRect( | |
Rect.fromLTWH(0, 0, text.width + _horizontalMargin * 2, text.height), | |
paint, | |
); | |
// [canvas] に白文字の'Hello'を描画 | |
text.paint(canvas, const Offset(_horizontalMargin, 0)); | |
} | |
@override | |
bool shouldRepaint(covariant CustomPainter oldDelegate) { | |
return true; | |
} | |
@override | |
SemanticsBuilderCallback get semanticsBuilder { | |
return (Size size) { | |
final rect = Rect.fromLTWH(0, 0, size.width, size.height); | |
return [ | |
CustomPainterSemantics( | |
rect: rect, | |
properties: const SemanticsProperties( | |
label: '赤い背景の上にハロー', | |
textDirection: TextDirection.ltr, | |
button: true, | |
), | |
) | |
]; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment