`LateInitializationError:字段'_image@63124145'尚未初始化。`在颤动中

时间:2021-07-11 09:03:25

标签: flutter dart

  • 我的 Flutter 应用程序有一个 image picker,但在将其更新为 null-safety 后,我已将 File _image; 更改为 late File _image; 并且我正在使用 Center(child: _buildImage()),显示所选图像。
  • 因此,在更改 null-safety 后,我收到错误 LateInitializationError: Field '_image@63124145' has not been initialized.。我无法理解我应该如何初始化我的 File _image; 变量
  • 代码
 // choose the image
  late File _image;

  Future<void> captureImage(ImageSource imageSource) async {
    try {
      final picker = ImagePicker();
      final pickedFile = await picker.getImage(
          source: ImageSource.gallery, maxHeight: 300, maxWidth: 300);
      setState(() {
        if (pickedFile != null) {
          _image = File(pickedFile.path);
        } else {
          print('No image selected.');
        }
      });
    } catch (e) {
      print(e);
    }
  }

  // displaying image
  Widget _buildImage() {
    // ignore: unnecessary_null_comparison
    if (_image != null) {
      return Image.file(_image);
    } else {
      return Text('Choose an image to show', style: TextStyle(fontSize: 18.0));
    }
  }
...
@override
  Widget build(BuildContext context) {
...
   final _height = MediaQuery.of(context).size.height;
    final _width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ...
                // choose image
                Container(
                  padding: EdgeInsets.symmetric(
                    vertical: _height * 0.015,
                  ),
                  child: FractionallySizedBox(
                    widthFactor: 1,
                    child: TextButton(
                      child: Text(
                        'Choose File',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 20,
                          fontFamily: 'Montserrat',
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onPressed: () => 
                      captureImage(ImageSource.gallery),
                    ),
                  ),
                ),
                SizedBox(
                  height: _height * 0.015,
                ),
                // display image
                Center(child: _buildImage()),

1 个答案:

答案 0 :(得分:1)

不要使用 late File _image; 使用可空文件,如 File? _image;

用于构建图像

 // displaying image
  Widget _buildImage() {
    // ignore: unnecessary_null_comparison
    if (_image != null) {
      return Image.file(_image!);
    } else {
      return Text('Choose an image to show', style: TextStyle(fontSize: 18.0));
    }
  }