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

How to set conditional statement for image in Flutter?

我有从 Flutter 资产设置图像的条件语句,但在 Scaffold body 中不起作用。

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

你可以这样做:

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() 方法 returns 什么都没有,而且你不能像这样使用它 new AssetImage(_setImage()) ,所以你必须制作类似 String _setImage() 的方法,其中 returns String (_backgroundImage),所以你可以直接在 new 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
            ),
          ),
        ),
      );
    }