Home > Enterprise >  flutter NetworkImage of CircleAvatar
flutter NetworkImage of CircleAvatar

Time:09-05

I want to replace the NetworkImage of CircleAvatar with an Icon only on error. This is  part of my code.

var db = FirebaseFirestore.instance;
  final docRef = db.collection("users").doc(uid);

  docRef.get().then(
    (DocumentSnapshot doc) {
      final data = doc.data() as Map<String, dynamic>;
   .
   .
   .
                     child: CircleAvatar(
                        radius: 40,
                        backgroundImage: NetworkImage(
                          data["imageUrl"],
                        ),
                      ),

I heard that Image.network has an errorbuilder property, but it is not applicable to CircleAvatar's backgroungImage.

CodePudding user response:

I have handled the network image issue related to 404 by using an errorBuilder.

Image.network('Your image url...',
    errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
        return Text('Your error widget...');
    },
),

OR

cached_network_image use this package like

CachedNetworkImage(
            imageUrl: widget.category.photo??"",
            errorWidget: (context, url, error) => const Icon(
                  Icons.error,
                  color: Colors.grey,
                ),
            color: widget.isSelected
                ? Colors.white
                : AppColors.fIconsAndTextColor),

CodePudding user response:

Instead of using CircleAvatar and NetworkImage, you can use this:

Container(
            height: 80,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.red,
              shape: BoxShape.circle,
            ),
            child: Image.network(
              '',
              errorBuilder: (context, error, stackTrace) {
                return Icon(Icons.error);
              },
            ),
          ),
  • Related