Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle 404 exception with CachedNetworkImage in flutter

When my image is not present in the server or if the image URL is not correct, I'm getting an exception error. How can I handle this error in flutter? Can I use future to handle this error? I tried the future but I couldn't figure it out.

Here is a screenshot:

enter image description here

Code

import 'package:cached_network_image/cached_network_image.dart';   
import './responsive/resp_safe_area.dart';
import './common/styling.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './responsive/size_config.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitUp,
  ]);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final appTitle = "Bigshopy";

  @override
  Widget build(BuildContext context) {
    try {
      return MediaQuery(
        data: MediaQueryData(),
        child: ResponsiveSafeArea(builder: (context, size) {
          SafeSizeConfig().init(size);
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            title: appTitle,
            theme: BigAppTheme.defaltTheme,
            home: Scaffold(
              appBar: AppBar(),
              body: SingleChildScrollView(
                child: Center(
                  child: Container(
                    child: CachedNetworkImage(
                      fit: BoxFit.fill,
                      imageUrl:
                          'http://192.168.1.3/bigshopy/assets/topItemCategory/login_main_img.png',
                      placeholder: (context, url) =>
                          CircularProgressIndicator(),
                      errorWidget: (context, url, error) =>
                          new Icon(Icons.error),
                    ),
                  ),
                ),
              ),
            ),
          );
        }),
      );
    } catch (error) {
      print(error);
    }
  }
}

Error Message

Exception has occurred. HttpExceptionWithStatus (HttpException: Invalid statusCode: 404, uri = http://192.168.1.3/assets/topItemCategory/login_main_img.png)

like image 681
Aagney K K Avatar asked Jun 20 '20 20:06

Aagney K K


Video Answer


1 Answers

The IDE is telling you that there is an exception, but actually it's ok. The reason is apparently because the Dart VM doesn't recognize it as a caught exception even though it is. Just press the continue button or uncheck the breakpoint for uncaught exceptions. You'll see that your errorWidget will show up.

enter image description here

The author of the plugin actually added a FAQ about this issue.

like image 144
Suragch Avatar answered Sep 16 '22 13:09

Suragch