oligazar
4/26/2019 - 4:40 AM

SafeImage no crash

import 'package:flutter/material.dart';

// https://github.com/flutter/flutter/issues/16592

class SafeImage extends StatefulWidget {
  final String url;
  final Widget image;
  final Widget placeholder;
  SafeImage(this.url, {this.image, this.placeholder});

  @override
  _SafeImageState createState() => _SafeImageState();
}

class _SafeImageState extends State<SafeImage> {
  bool hasError = false;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: precacheImage(NetworkImage(widget.url), context,
          onError: (e, _) => setState(() => hasError = true)
      ),
      builder: (context, snap) {
        switch (snap.connectionState) {
          case ConnectionState.done:
            return hasError ? widget.placeholder : widget.image;
          default:
            return widget.placeholder;
        }
      },
    );
  }
}