Created
February 24, 2026 18:29
-
-
Save iBelow/da83930af8812e014b73210f170c57b6 to your computer and use it in GitHub Desktop.
Flutter Avatar generator snippet
This file contains hidden or 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
| import 'package:flutter/material.dart'; | |
| void main() { | |
| runApp(const MaterialApp(home: AvatarPreview())); | |
| } | |
| class AvatarPreview extends StatelessWidget { | |
| const AvatarPreview({super.key}); | |
| Color $avatarColor(String $t, Brightness $b) { | |
| var $h = 0; | |
| for (final $u in $t.trim().toUpperCase().codeUnits) { | |
| $h = ($h ^ $u) + (($h << 5) | ($h >> 27)); | |
| } | |
| $h &= 0xFFFFFFFF; | |
| final $hue = ($h & 0x1FF) % 360; // 9 → 0–511 → mod 360 | |
| const $s = 0.65; | |
| final $l = $b == Brightness.dark ? 0.60 : 0.50; | |
| return HSLColor.fromAHSL(1, $hue.toDouble(), $s, $l).toColor(); | |
| } | |
| Color $textColor(Color $bg) { | |
| final $c = $bg.value; | |
| final $r = ($c >> 16) & 0xFF; | |
| final $g = ($c >> 8) & 0xFF; | |
| final $b = $c & 0xFF; | |
| final $lum = (54 * $r + 183 * $g + 19 * $b) >> 8; | |
| return $lum > 128 ? Colors.black : Colors.white; | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| final String name = "John Doe"; | |
| final brightness = Theme.of(context).brightness; | |
| final Color bgColor = $avatarColor(name, brightness); | |
| final Color textColor = $textColor(bgColor); | |
| return Scaffold( | |
| body: Center( | |
| child: CircleAvatar( | |
| radius: 50, | |
| backgroundColor: bgColor, | |
| child: Text( | |
| name.$i(), | |
| style: TextStyle( | |
| color: textColor, | |
| fontSize: 40, | |
| fontWeight: FontWeight.bold, | |
| ), | |
| ), | |
| ), | |
| ), | |
| ); | |
| } | |
| } | |
| extension StringInitials on String { | |
| String $i() => trim() | |
| .toUpperCase() | |
| .split(RegExp(r'\s+')) | |
| .where((e) => e.isNotEmpty) | |
| .take(2) | |
| .map((e) => e.characters.first) | |
| .join(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment