user_avatar.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'package:appflowy/generated/flowy_svgs.g.dart';
  2. import 'package:appflowy/generated/locale_keys.g.dart';
  3. import 'package:appflowy/util/color_generator/color_generator.dart';
  4. import 'package:easy_localization/easy_localization.dart';
  5. import 'package:flowy_infra/size.dart';
  6. import 'package:flowy_infra_ui/style_widget/text.dart';
  7. import 'package:flutter/material.dart';
  8. const double _smallSize = 28;
  9. const double _largeSize = 56;
  10. class UserAvatar extends StatelessWidget {
  11. const UserAvatar({
  12. super.key,
  13. required this.iconUrl,
  14. required this.name,
  15. this.isLarge = false,
  16. });
  17. final String iconUrl;
  18. final String name;
  19. final bool isLarge;
  20. @override
  21. Widget build(BuildContext context) {
  22. final size = isLarge ? _largeSize : _smallSize;
  23. if (iconUrl.isEmpty) {
  24. final String nameOrDefault = _userName(name);
  25. final Color color = ColorGenerator().generateColorFromString(name);
  26. const initialsCount = 2;
  27. // Taking the first letters of the name components and limiting to 2 elements
  28. final nameInitials = nameOrDefault
  29. .split(' ')
  30. .where((element) => element.isNotEmpty)
  31. .take(initialsCount)
  32. .map((element) => element[0].toUpperCase())
  33. .join('');
  34. return Container(
  35. width: size,
  36. height: size,
  37. alignment: Alignment.center,
  38. decoration: BoxDecoration(
  39. color: color,
  40. shape: BoxShape.circle,
  41. ),
  42. child: FlowyText.semibold(
  43. nameInitials,
  44. color: Colors.white,
  45. fontSize: isLarge
  46. ? nameInitials.length == initialsCount
  47. ? 20
  48. : 26
  49. : nameInitials.length == initialsCount
  50. ? 12
  51. : 14,
  52. ),
  53. );
  54. }
  55. return SizedBox.square(
  56. dimension: size,
  57. child: ClipRRect(
  58. borderRadius: Corners.s5Border,
  59. child: CircleAvatar(
  60. backgroundColor: Colors.transparent,
  61. child: FlowySvg(
  62. FlowySvgData('emoji/$iconUrl'),
  63. blendMode: null,
  64. ),
  65. ),
  66. ),
  67. );
  68. }
  69. /// Return the user name, if the user name is empty,
  70. /// return the default user name.
  71. String _userName(String name) =>
  72. name.isEmpty ? LocaleKeys.defaultUsername.tr() : name;
  73. }