如何在 flutter 中动态分配图像?例如:
final topContent = Stack(
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 10.0),
height: MediaQuery.of(context).size.height * 0.5,
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage(lesson.imagePath),
fit: BoxFit.cover,
),
)),
Container(
height: MediaQuery.of(context).size.height * 0.5,
padding: EdgeInsets.all(40.0),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(color: Color.fromRGBO(58, 66, 86, .9)),
child: SingleChildScrollView(
controller: _scrollController,
child: Center(
child: topContentText,
),
),
),
Positioned(
left: 8.0,
top: 60.0,
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back, color: Colors.white),
),
)
],
);
现在,开始时的图像 lesson.imagePath
是我想要动态更改的内容。我尝试使用 setState()
但它给了我一个错误:
The expression here is a type of void and cannot be used
image: setState ((){
if (someCondition) {
return new AssetImage(lesson.imagePath);
}
}),
最佳答案
你的setState调用是错误的!最简单的方法是将图像设置为小部件的状态,并在 setState
调用中更新此图像。 setState
方法不会返回任何内容,它只是重建您的小部件。
在您的 _WidgetState 类中,您声明为成员:
AssetImage _imageToShow;
您可以在 initState
方法中提供初始图像。
@override
initState(){
_imageToShow = AssetImage('youAssetImage');
}
您的容器小部件应声明为:
Container(
padding: EdgeInsets.only(left: 10.0),
height: MediaQuery.of(context).size.height * 0.5,
decoration: new BoxDecoration(
image: new DecorationImage(
image: _imageToShow,
fit: BoxFit.cover,
),
)),
),
要使用 setState 调用更新您的图像,您只需要:
void updateImage() {
setState ((){
if (someCondition) {
_imageToShow = new AssetImage(lesson.imagePath);
}
});
}
但请记住,有些东西必须调用 updateImage
方法。
关于flutter - 在 flutter 中动态分配图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325870/