带有 Uint8List 的图像为空 - Flutter
Posted
技术标签:
【中文标题】带有 Uint8List 的图像为空 - Flutter【英文标题】:Image is null with Uint8List - Flutter 【发布时间】:2020-07-18 11:15:13 【问题描述】:我正在尝试将图像编码为 Uint8List,但它给了我一个 null
List<int> bytes;
I.Image _img;
@override
void initState()
super.initState();
WidgetsFlutterBinding.ensureInitialized();
String file = 'lib/graphics/logo.png';
readFileAsync(file);
Future<dynamic> readFileAsync(String filePath) async
var imageData = await rootBundle.load('lib/graphics/logo.png');
bytes = Uint8List.view(imageData.buffer);
_img = I.decodeImage(bytes);
并从小部件树中调用它
Container(
child: Image.memory(_img.getBytes()),
),
错误
I/flutter (26125): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (26125): The following NoSuchMethodError was thrown building LayoutBuilder:
I/flutter (26125): The method 'getBytes' was called on null.
I/flutter (26125): Receiver: null
I/flutter (26125): Tried calling: getBytes()
【问题讨论】:
您的资产或资产路径是否在您的 pubspec.yaml 中声明? 资产:- lib/graphics/logo.png 【参考方案1】:你得到一个 null 因为 load
方法是一个 Future
并且你不需要在你的构建方法上等待它。
您必须检查 _img
是否为空,如果是,则显示另一个小部件,如 Text 或 CircularProgressIndicator:
Container(
child: _img ? Image.memory(_img.getBytes()) : Text('loading...'),
),
之后,您需要在readFileAsync
方法中调用setState()
方法来重建您的小部件:
setState()
_img = I.decodeImage(bytes);
【讨论】:
谢谢...它现在可以工作...我看到它没有将它保存到全局变量...但是如果我使用 set state 则它可以工作...谢谢反馈以上是关于带有 Uint8List 的图像为空 - Flutter的主要内容,如果未能解决你的问题,请参考以下文章
从 Flutter 中的 Uint8List 数据更改图像大小