gpt4 book ai didi

Dart - 在初始值设定项中只能访问静态成员

转载 作者:IT王子 更新时间:2023-10-29 06:47:45 24 4
gpt4 key购买 nike

我正在尝试使用以下代码

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,),
),
),
);

这里已经有问题了, Error: Only static members can be accessed in initializers what does this mean?关于这个问题,但是,我真的应该为此使用“SingleTickerProviderStateMixin”吗?另外,这与单例有关吗? (我还在学习编程)

尝试以下答案后出错: enter image description here

最佳答案

final itemImage = ...

初始化一个类级别的字段。此代码在构造函数完成和对象完全初始化之前执行,因此禁止访问 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,
),
),
),
);

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

关于Dart - 在初始值设定项中只能访问静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50682496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com