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

80 lines
2.1 KiB
Dart
Raw Normal View History

2022-10-31 17:15:05 +01:00
// SPDX-FileCopyrightText: 2022 Iconica
//
// SPDX-License-Identifier: BSD-3-Clause
2022-11-24 14:56:21 +01:00
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_profile/src/models/user.dart';
class Avatar extends StatelessWidget {
const Avatar({
Key? key,
2022-11-24 14:56:21 +01:00
this.user,
this.size = 100,
this.avatarBackgroundColor,
}) : super(key: key);
2022-11-24 14:56:21 +01:00
final User? user;
final double size;
final Color? avatarBackgroundColor;
@override
Widget build(BuildContext context) {
var imageProvider = _getImageProvider(user);
2022-11-24 14:56:21 +01:00
var hasImage = imageProvider != null;
var hasNames =
user != null && (user!.firstName != null || user!.lastName != null);
2022-11-24 14:56:21 +01:00
return Container(
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: avatarBackgroundColor ??
(!hasImage && hasNames
? _generateColorWithIntials(user!.firstName, user!.lastName)
: null),
2022-11-24 14:56:21 +01:00
image: hasImage
? DecorationImage(
image: imageProvider,
fit: BoxFit.contain,
2022-11-24 14:56:21 +01:00
)
: null,
),
child: hasImage || !hasNames
? null
: Center(
child: Text(
style: TextStyle(
fontSize: size * 0.4,
),
user!.initials,
),
2022-11-24 11:00:38 +01:00
),
2022-11-24 14:56:21 +01:00
);
}
2022-11-24 14:56:21 +01:00
ImageProvider? _getImageProvider(User? user) {
if (user?.image != null) {
return MemoryImage(user!.image!);
} else if (user?.imageUrl != null) {
return CachedNetworkImageProvider(user!.imageUrl!);
}
return null;
}
Color _generateColorWithIntials(String? firstName, String? lastName) {
2022-10-28 10:27:44 +02:00
var idFirstName = 0;
var idLastName = 0;
if (firstName?.isNotEmpty ?? false) {
idFirstName = firstName!.toLowerCase().codeUnitAt(0);
}
if (lastName?.isNotEmpty ?? false) {
idLastName = lastName!.toLowerCase().codeUnitAt(0);
}
2022-10-28 10:27:44 +02:00
return Colors
.primaries[(idFirstName + idLastName) % Colors.primaries.length];
}
}