Uint8List图片为空-Flutter

多汉·史密斯(Dohan Smit)

我正在尝试将图像编码为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()
佩罗奇

您会得到一个空值,因为该load方法是a,Future并且您不必在构建方法上等待它。

您必须检查是否_img为空,如果是,则显示另一个小部件,例如Text或CircularProgressIndicator:

Container(
  child: _img ? Image.memory(_img.getBytes()) : Text('loading...'),
), 

之后,您需要调用setState()方法以在您方法中重建窗口小部件readFileAsync

setState() {
  _img = I.decodeImage(bytes);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章