1

我正在尝试将图像编码为 Uint8List 但它给了我一个空值

  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()
4

1 回答 1

2

你得到一个 null 因为load方法是 aFuture并且你不需要在你的 build 方法上等待它。

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

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

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

setState() {
  _img = I.decodeImage(bytes);
}
于 2020-04-07T07:13:12.987 回答