skip to Main Content

Code
How do I show a different image if a _readProfile is null

I tried the picture above and it is erroring out

4

Answers


  1. You need to create a method with return Widget.

    And it will work as below

      Widget getImage() {
        if (_readProfile != null) {
          return Image.network('YOUR LINK');
        } else {
          return Image.asset('URL FROM ASSET FOLDER');
        }
      }
    

    Then you just need to call this method

    Container(
      child: getImage(),
    )
    

    It will work for you.

    Login or Signup to reply.
  2. You can do it in one line by using ?? – if null operator

    Image.network(_readProfile?.image.toString() ?? 'Your link')
    
    Login or Signup to reply.
  3. add a default image in you app
    for exemple

    const String _defaultImage =
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQK_rZWRT_RXyeRBWmGHQB52XAdSfSFFbIMHyCqWZ0&s";
    

    now you can use it in Image.network

    Image.network(
            a ?? _defaultImage,           
          ),
    

    and you can add a default icon if the error will come from the server

     Image.network(
            a ?? _defaultImage,
            errorBuilder: (context, error, stackTrace) => const Icon(Icons.person)),
          ),
    
    Login or Signup to reply.
  4. You can use errorBuilder property:

    Image.network(
          "Image URL",
          errorBuilder: (context, error,_){
            return Image.asset("Image URL");
          },
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search