Flutter异常生成器不断被调用 [英] Flutter exception Builder keeps being called

查看:295
本文介绍了Flutter异常生成器不断被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flutter Image.file()在我的应用程序中显示图像。我还使用errorBuilder处理任何崩溃并向用户显示一条消息。


执行这些步骤时遇到问题。


  1. 加载有效的图像

  2. 将损坏的图像加载到同一Image.File()小部件中

  3. 加载原始的好图像返回到相同的Image.File()小部件中

似乎在传入损坏的照片(步骤2)之后,每次文件更改都会导致在显示的错误生成器中,而不是在新的良好图像中。


如果我没有在步骤2中传递损坏的照片,则照片会像应该的那样变化。这是Flutter Image()的错误,还是在进入errorBuilder后应该做些什么呢?


这是我当前的设置。

  Image.file(
文件,
适合:BoxFit.cover,
errorBuilder:(BuildContext上下文,对象异常,StackTrace stackTrace){
print(未能初始化文件);
print(stackTrace);
//一旦发生错误,它总是在这里
返回Text(发生错误)。 );
},
);

在传入/损坏文件后/之后,我在所有文件上收到的实际错误都是

 无法实例化图像编解码器。 




UPDATE


我写了一个dartpad



完整代码

  import'package:flutter / material.dart' ; 

void main()=> runApp(MyApp());

类MyApp扩展了StatelessWidget {
@override
Widget build(BuildContext context){
return MaterialApp(
title:'Flutter Demo',
debugShowCheckedModeBanner:false,
主题:ThemeData(
primarySwatch :Colors.blue,
),
home:MyHomePage(title:'Flutter Demo Home Page'),
);
}
}

类MyHomePage扩展了StatefulWidget {
MyHomePage({Key key,this.title}):super(key:key);

最终字符串标题;

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

类_MyHomePageState扩展State< MyHomePage> {
字符串_goodImageOne =
https://upload.wikimedia.org/wikipedia/commons/6/69/June_odd-eyed-cat_cropped.jpg;
字符串_corruptImage =
https://srv-file16.gofile.io/download/hwTzLI/cat_corrupt.jpg;
字符串_goodImageTwo =
https://upload.wikimedia.org/wikipedia/commons/c/c7/Tabby_cat_with_blue_eyes-3336579.jpg;

字符串_selectedImageURL;

@override
void initState(){
super.initState();
_selectedImageURL = _goodImageOne;
}

void _changeFile(String newUrl){
setState((){
_selectedImageURL = newUrl;
});
}

@override
小部件构建(BuildContext上下文){
return Scaffold(
appBar:AppBar(
title:Text(widget .title),
),
正文:Center(
子级:Column(
mainAxisAlignment:MainAxisAlignment.center,
子级:< Widget> [[
Image.network(
_selectedImageURL,
键:UniqueKey(),
高度:300,
宽度:200,
loadingBuilder:(BuildContext上下文,Widget子,
ImageChunkEvent loadingProgress){
if(loadingProgress == null)返回子级;
return Center(
子级:CircularProgressIndicator(
值:loadingProgress.expectedTotalBytes!= null
?loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBy tes
:null,
));
},
errorBuilder:(BuildContext上下文,对象异常,
StackTrace stackTrace){
return Text( Cannot display url);
},
),
Expanded(child:Container()),
RaisedButton(
onPressed:()=> _changeFile(_goodImageOne),
子:Text( Good Image),
),
RaisedButton(
onPressed:()=> _changeFile(_corruptImage),
子:Text(损坏的图片),
),
RaisedButton(
onPressed:()=> _changeFile(_goodImageTwo),
子级:Text(良好图片2),
),
],
),
),
);
}
}


I am using a flutter Image.file() to show an Image in my app. I am also using the errorBuilder to handle any crashes and show a message to the user.

I encounter a problem when i do these steps.

  1. Load a good image that works
  2. Load a corrupt image into the same Image.File() widget
  3. Load the original good image back into the same Image.File() widget

It seems every file change after the corrupt photo is passed in (step 2) will result in the error builder being shown and not the new good image.

If i don't pass in the corrupt photo in step 2, the photo changes like it should. Is this a bug with the flutter Image() or should I be doing something after it goes into the errorBuilder.

Here is my current setup.

Image.file(
        file,
        fit: BoxFit.cover,
        errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
          print("Failed to initialise the file");
          print(stackTrace);
          //  Once an error occurs it always goes in here 
          return Text("an error occurred");
        },
      );

The actual error I receive on all file changes when/after the corrupt file is passed in is

Could not instantiate image codec.


UPDATE

I have wrote a dartpad that shows the problem i am experiencing.

https://dartpad.dev/98c2dacb481c088dfd2e5bee490f45ed

If you click

  1. Good Image
  2. Good Image 2
  3. Good Image
  4. Good Image 2

The images cycle correctly... which works.

if you then click "Corrupt Image" which will attempt to load a corrupt jpeg file the error builder will fire.

If you then click "Good Image" or "Good Image 2" they no longer build and the Image is stuck loading the error builder everytime... How can I get it to then load one of the good images again?

Please let me know if I haven't been clear and I will add more information :)

Thanks a lot

解决方案

You can copy paste run full code below
This error can be fixed with add key: UniqueKey(),
I have test it with DardPad works fine
code snippet

Image.network(
          _selectedImageURL,
          key: UniqueKey(),

working demo

full code

import 'package:flutter/material.dart'; 

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String _goodImageOne =
      "https://upload.wikimedia.org/wikipedia/commons/6/69/June_odd-eyed-cat_cropped.jpg";
  String _corruptImage =
      "https://srv-file16.gofile.io/download/hwTzLI/cat_corrupt.jpg";
  String _goodImageTwo =
      "https://upload.wikimedia.org/wikipedia/commons/c/c7/Tabby_cat_with_blue_eyes-3336579.jpg";

  String _selectedImageURL;

  @override
  void initState() {
    super.initState();
    _selectedImageURL = _goodImageOne;
  }

  void _changeFile(String newUrl) {
    setState(() {
      _selectedImageURL = newUrl;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.network(
              _selectedImageURL,
              key: UniqueKey(),
              height: 300,
              width: 200,
              loadingBuilder: (BuildContext context, Widget child,
                  ImageChunkEvent loadingProgress) {
                if (loadingProgress == null) return child;
                return Center(
                    child: CircularProgressIndicator(
                  value: loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes
                      : null,
                ));
              },
              errorBuilder: (BuildContext context, Object exception,
                  StackTrace stackTrace) {
                return Text("Cannot display url");
              },
            ),
            Expanded(child: Container()),
            RaisedButton(
              onPressed: () => _changeFile(_goodImageOne),
              child: Text("Good Image"),
            ),
            RaisedButton(
              onPressed: () => _changeFile(_corruptImage),
              child: Text("Corrupt Image"),
            ),
            RaisedButton(
              onPressed: () => _changeFile(_goodImageTwo),
              child: Text("Good Image 2"),
            ),
          ],
        ),
      ),
    );
  }
}

这篇关于Flutter异常生成器不断被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆