flutter_profile/lib/src/widgets/avatar/avatar.dart

86 lines
2.1 KiB
Dart
Raw Normal View History

2022-08-26 15:31:42 +02:00
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:profile/src/widgets/avatar/avatar_style.dart';
class Avatar extends StatelessWidget {
const Avatar({
Key? key,
this.image,
this.firstName,
this.lastName,
2022-08-26 15:31:42 +02:00
this.avatar,
this.style = const AvatarStyle(),
}) : super(key: key);
final Uint8List? image;
final String? firstName;
final String? lastName;
2022-08-26 15:31:42 +02:00
final Widget? avatar;
final AvatarStyle style;
@override
Widget build(BuildContext context) {
return Column(
children: [
_avatar(),
const SizedBox(
height: 16,
),
if (firstName != null || lastName != null)
2022-08-26 15:31:42 +02:00
Text(
'${firstName ?? ''} ${lastName ?? ''}',
2022-08-26 15:31:42 +02:00
style: style.displayNameStyle,
)
],
);
}
Widget _avatar() {
if (avatar != null) {
return avatar!;
}
if (image != null && image!.isNotEmpty) {
return Container(
width: style.width,
height: style.height,
decoration: BoxDecoration(
2022-08-26 15:31:42 +02:00
shape: BoxShape.circle,
image: DecorationImage(
image: MemoryImage(image!),
fit: BoxFit.fill,
),
2022-08-26 15:31:42 +02:00
),
);
} else if (firstName != null || lastName != null) {
2022-08-26 15:31:42 +02:00
return Container(
width: style.width,
height: style.height,
decoration: BoxDecoration(
color: _generateColorWithIntials(firstName, lastName),
2022-08-26 15:31:42 +02:00
shape: BoxShape.circle,
),
child: Center(
child: Text(
style: const TextStyle(fontSize: 40),
_getInitials(firstName, lastName),
2022-08-26 15:31:42 +02:00
),
),
);
} else {
return Container();
2022-08-26 15:31:42 +02:00
}
}
String _getInitials(String? firstName, String? lastName) {
return (firstName?[0] ?? '') + (lastName?[0] ?? '');
2022-08-26 15:31:42 +02:00
}
Color _generateColorWithIntials(String? firstName, String? lastName) {
var uniqueInitialId = (firstName?.toLowerCase().codeUnitAt(0) ?? 0) +
(lastName?.toLowerCase().codeUnitAt(0) ?? 0);
2022-08-26 15:31:42 +02:00
return Colors.primaries[uniqueInitialId % Colors.primaries.length];
}
}