Image 如何在颤振中为图像设置条件语句?
我有条件语句来设置来自颤振资源的图像,但在脚手架主体中不起作用 如何在颤振中为图像设置条件语句Image 如何在颤振中为图像设置条件语句?,image,dart,conditional,flutter,assets,Image,Dart,Conditional,Flutter,Assets,我有条件语句来设置来自颤振资源的图像,但在脚手架主体中不起作用 如何在颤振中为图像设置条件语句 String _backgroundImage; void _setImage() { String _mTitle = "${widget.title.data}"; if(_mTitle == “Goodmorrning”) { _backgroundImage = "assets/mobil_hello/goodmorrning.jpg"; } else if(_mTit
String _backgroundImage;
void _setImage() {
String _mTitle = "${widget.title.data}";
if(_mTitle == “Goodmorrning”) {
_backgroundImage = "assets/mobil_hello/goodmorrning.jpg";
} else if(_mTitle == “Good day”) {
_backgroundImage = "assets/mobil_hello/goodday.jpg";
}
print("_mTitle: $_mTitle"); // works
print("_backgroundImage: $_backgroundImage"); // works
}
Widget build(BuildContext contest) {
return Scaffold(
body: new Container(
decoration: BoxDecoration(
color: widget.backgroundColor,
image: new DecorationImage(
fit: BoxFit.cover,
image: new AssetImage("$_backgroundImage") // not working
),
),
),
);
}
你可以这样做:
String _setImage() {
String _mTitle = "${widget.title.data}";
if(_mTitle == “Goodmorrning”) {
return "assets/mobil_hello/goodmorrning.jpg";
} else if(_mTitle == “Good day”) {
return "assets/mobil_hello/goodday.jpg";
}
print("_mTitle: $_mTitle"); // works
print("_backgroundImage: $_backgroundImage"); // works
}
Widget build(BuildContext contest) {
return Scaffold(
body: new Container(
decoration: BoxDecoration(
color: widget.backgroundColor,
image: new DecorationImage(
fit: BoxFit.cover,
image: new AssetImage(_setImage()) // not working
),
),
),
);
}
在这里,您创建了void _setImage()方法,该方法不返回任何内容,并且您不能像这样使用它新资产评估(_setImage()),因此您必须创建类似字符串_setImage()的方法,该方法返回字符串(_backgroundImage()),因此您可以在新资产评估(_setImage())中直接调用该方法 用以下代码替换您的代码:
import 'package:flutter/material.dart';
String _backgroundImage;
String _setImage() {
String _mTitle = "${widget.title.data}";
if(_mTitle == "Goodmorrning") {
_backgroundImage = "assets/mobil_hello/goodmorrning.jpg";
} else if(_mTitle == "Good day") {
_backgroundImage = "assets/mobil_hello/goodday.jpg";
}
print("_mTitle: $_mTitle");
print("_backgroundImage: $_backgroundImage");
return _backgroundImage; // here it returns your _backgroundImage value
}
Widget build(BuildContext contest) {
return Scaffold(
body: new Container(
decoration: BoxDecoration(
color: widget.backgroundColor,
image: new DecorationImage(
fit: BoxFit.cover,
image: new AssetImage(_setImage()) //call your method here
),
),
),
);
}
如果您使用的是
statefullwidget
,那么应该在setimage中调用setState。如果(_mTitle==“Goodmorrning”){setState(({u backgroundImage=“assets/mobil\u hello/Goodmorrning.jpg”;})与elseif
块相同