Dart - 只能在初始化程序中访问静态成员

Jac*_*Boi 3 dart flutter

我正在尝试使用以下代码

class NewItemCreate extends StatefulWidget{

  @override
  NewItemCreateState createState() => new NewItemCreateState();
}

class NewItemCreateState extends State<NewItemCreate>
{

  File _image;
  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      _image = image;
    });
    print(_image.path);
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.yellow,

        appBar: new AppBar(
          title: new Text("Report"),
          elevation: 5.0,
        ),
      body:
      Center  (
          child: ListView(
            padding: EdgeInsets.only(left: 24.0, right: 24.0),
            shrinkWrap: true,
            children: <Widget>[
              itemImage,
              SizedBox(height: 18.0),
              itemName,
              SizedBox(height: 18.0),
              itemLocation,
              SizedBox(height: 18.0),
              itemLocation,
              SizedBox(height: 18.0),
              itemTime,
              SizedBox(height: 18.0),
              Report,
              SizedBox(height: 38.0),
            ],
          )
      )
    );

  }

  final itemImage =       Padding(
    padding: EdgeInsets.symmetric(vertical: 25.0),
    child: Material(
      borderRadius: BorderRadius.circular(30.0),
      shadowColor: Colors.lightBlueAccent.shade100,
      elevation: 5.0,
      child: MaterialButton(
        minWidth: 200.0,
        height: 300.0,
        onPressed: (){
          getImage();
        },
        color: Colors.lightGreenAccent,
        child:
        new Icon(Icons.add_a_photo, size: 150.0,color: Colors.blue,),
      ),
    ),
  );
Run Code Online (Sandbox Code Playgroud)

这里已经有一个问题, 错误:在初始化程序中只能访问静态成员,这是什么意思? 关于这个问题,但是,我真的应该使用"SingleTickerProviderStateMixin"吗?此外,这与单身人士有关吗?(我还在学习编程)

尝试以下答案后出错: 在此输入图像描述

Gün*_*uer 7

final itemImage = ...
Run Code Online (Sandbox Code Playgroud)

初始化一个类级字段.此代码在构造函数完成并且对象完全初始化之前执行,因此this.禁止访问(隐式或显式),因为无法保证您尝试访问的内容已经初始化.

无论如何,以这种方式创建和缓存小部件总体上是一个坏主意.而是使它成为一种方法:

Widget buildItemImage(BuildContext context) => Padding(
    padding: EdgeInsets.symmetric(vertical: 25.0),
    child: Material(
        borderRadius: BorderRadius.circular(30.0),
        shadowColor: Colors.lightBlueAccent.shade100,
        elevation: 5.0,
        child: MaterialButton(
            minWidth: 200.0,
            height: 300.0,
            onPressed: () {
                getImage();
            },
            color: Colors.lightGreenAccent,
            child: new Icon(Icons.add_a_photo, size: 150.0,color: Colors.blue,
        ),
      ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

这样,代码首先在buildItemImage(context)被调用时执行,而不是在创建对象实例时执行.此时,保证可以保存以进行访问this..