为什么Image.network
的errorBuilder
在DecorationImage
时不被调用?
在Image.network
中发生的错误调用DecorationImage
中的onError
。所以我不能用另一个小部件替换失败的图像。
下面是处理这种情况的代码。我从errorBuilder的文档中获取了示例,并对其进行了修改,使Image.network
位于DecorationImage
中。见下文:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: Scaffold(
body: Center(
child: MyStatelessWidget(),
),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(),
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
onError: (obj, st) {
print('ONERROR-ONERROR-ONERROR');
},
image: Image.network(
'https://example.does.not.exist/image.jpg',
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
// Appropriate logging or analytics, e.g.
// myAnalytics.recordError(
// 'An error occurred loading "https://example.does.not.exist/image.jpg"',
// exception,
// stackTrace,
// );
return const Text('ERROR');
},
).image
)
),
child: const SizedBox(height: 200, width: 200),
);
}
}
您正在使用返回ImageProvider
的image:Image.network().image
。这意味着image
只有在没有错误并且图像加载完美的情况下才会从Image.network
获得。当问题发生时,您可以看到onError
消息。
现在对于用例errorBuilder
返回一个不能在image
上直接分配的小部件。
这可能是为了处理错误而过度设计的调用。
@override
Widget build(BuildContext context) {
final dImage = DecorationImage(
onError: (obj, st) {
print('ONERROR-ONERROR-ONERROR');
},
image: Image.network(
'h .exist/image.jpg',
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
debugPrint("onError B");
return Text("rr");
},
).image,
);
return Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(),
borderRadius: BorderRadius.circular(20),
image: dImage.onError != null
? DecorationImage(
image: NetworkImage(imgUrl), //default image URL on null case
)
: dImage,
),
child: const SizedBox(height: 200, width: 200),
);
}
如果我需要覆盖,我更喜欢使用容器子堆栈。
我们已经有child
选项和简化的情况。这是一种简单明了的方法,你可以通过阅读代码来判断,而不必滚动鼠标。
return Container(
height: 200,
width: 200,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(),
borderRadius: BorderRadius.circular(20),
),
child: Image.network(
'h .exist/image.jpg',
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
debugPrint("onError B");
return Center(child: Text("Error"));
},
),
);