在DecorationImage中没有调用Image.network的errorBuilder回调



为什么Image.networkerrorBuilderDecorationImage时不被调用?

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),
);
}
}

您正在使用返回ImageProviderimage: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"));
},
),
);

最新更新