如何在Flutter中设置图像的条件语句?

时间:2018-10-01 06:02:13

标签: image dart conditional flutter assets

我有条件声明可以从Flutter资产设置图像,但是不能在Scaffold主体中工作。

如何在Flutter中为图像设置条件语句?

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

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

答案 1 :(得分:0)

在这里,您创建了void _setImage()方法,该方法什么也不返回,并且您也不能像这样 new AssetImage(_setImage())那样使用它,因此,您必须制作类似于String _setImage( ),它返回String(_backgroundImage),因此您可以在新的AssetImage(_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
            ),
          ),
        ),
      );
    }