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

83 lines
2.1 KiB
Dart
Raw Normal View History

2022-08-26 15:31:42 +02:00
import 'package:flutter/material.dart';
2022-10-21 10:42:32 +02:00
import 'package:flutter_profile/src/models/user.dart';
2022-09-21 14:37:16 +02:00
import 'package:flutter_profile/src/widgets/avatar/avatar_style.dart';
2022-08-26 15:31:42 +02:00
2022-10-21 10:42:32 +02:00
class AvaterWrapper extends StatelessWidget {
const AvaterWrapper({
2022-08-26 15:31:42 +02:00
Key? key,
2022-10-21 10:42:32 +02:00
required this.user,
2022-08-26 15:31:42 +02:00
this.avatar,
this.style = const AvatarStyle(),
}) : super(key: key);
2022-10-21 10:42:32 +02:00
final User user;
2022-08-26 15:31:42 +02:00
final Widget? avatar;
final AvatarStyle style;
@override
2022-10-21 10:42:32 +02:00
Widget build(BuildContext context) => Column(
children: [
avatar ?? _generateAvatar(),
const SizedBox(
height: 16,
),
if (user.firstName != null || user.firstName != null)
Text(
user.displayName,
style: style.displayNameStyle,
)
],
);
2022-08-26 15:31:42 +02:00
2022-10-21 10:42:32 +02:00
ImageProvider? _getImageProvider() {
if (user.image != null) {
return MemoryImage(user.image!);
} else if (user.imageUrl != null) {
return NetworkImage(user.imageUrl!);
2022-08-26 15:31:42 +02:00
}
2022-10-21 10:42:32 +02:00
return null;
}
Widget _generateAvatar() {
var imageProvider = _getImageProvider();
if (imageProvider != null) {
2022-08-26 15:31:42 +02:00
return Container(
width: style.width,
height: style.height,
decoration: BoxDecoration(
2022-08-26 15:31:42 +02:00
shape: BoxShape.circle,
image: DecorationImage(
2022-10-21 10:42:32 +02:00
image: imageProvider,
2022-09-28 11:00:11 +02:00
fit: BoxFit.cover,
),
2022-08-26 15:31:42 +02:00
),
);
2022-10-21 10:42:32 +02:00
} else if (user.firstName != null || user.lastName != null) {
2022-08-26 15:31:42 +02:00
return Container(
width: style.width,
height: style.height,
decoration: BoxDecoration(
2022-10-21 10:42:32 +02:00
color: _generateColorWithIntials(user.firstName, user.lastName),
2022-08-26 15:31:42 +02:00
shape: BoxShape.circle,
),
child: Center(
child: Text(
style: const TextStyle(fontSize: 40),
2022-10-21 10:42:32 +02:00
user.initials,
2022-08-26 15:31:42 +02:00
),
),
);
}
2022-10-21 10:42:32 +02:00
return Container();
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];
}
}