首页 > 解决方案 > 如何更新另一个自定义 Flutter 小部件中存在的图像路径?

问题描述

我试图使用 Flutter 的桌面实现创建一个应用程序,该应用程序将使用 JSON 文件读取图像的路径,将路径传递给自定义小部件,小部件将在容器内显示带有悬停动画的图像。

声明的变量如下:

String characterName = 'Elise';
var skill_icon_path =
            characterData[characterName]['ability 1']['icon path'];

然后使用以下代码将其传递到自定义小部件:

ButtonAnimation(
                imagePath: skill_icon_path,
                height: 70,
                width: 70,
              ),

ButtonAnimation 小部件的代码如下:

import 'package:flutter/material.dart';

class ButtonAnimation extends StatefulWidget {
  ButtonAnimation({Key key, this.imagePath, this.height, this.width})
      : super(key: key);
  final String imagePath;
  final double height;
  final double width;

  @override
  buttonAnimationState createState() =>
      buttonAnimationState(imagePath, height, width);
}

class buttonAnimationState extends State<ButtonAnimation> {
  final String imageSrc;
  buttonAnimationState(this.imageSrc, this.height, this.width);
  final double height;
  final double width;
  bool isHover = false;
  bool animation_ended = false;
  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      width: width,
      child: InkWell(
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(
                  width: 1, color: isHover ? Colors.red : Colors.grey)),
          child: Stack(
            children: [
              AnimatedContainer(
                duration: Duration(milliseconds: 200),
                padding: EdgeInsets.all(10),
                child: Image(
                  image: AssetImage(imageSrc),
                  color: Colors.grey,
                ),
              ),
              AnimatedContainer(
                padding: EdgeInsets.all(10),
                onEnd: () {
                  setState(() {
                    animation_ended = true;
                  });
                },
                duration: Duration(milliseconds: 50),
                color: Colors.red,
                child: Visibility(
                  visible: animation_ended,
                  child: Image(
                    image: AssetImage(imageSrc),
                    color: Colors.white,
                  ),
                ),
                height: double.infinity,
                width: isHover ? width : 0,
              )
            ],
          ),
        ),
        onTap: () {},
        onHover: (value) {
          setState(() {
            isHover = !isHover;
            print(imageSrc);
          });
        },
      ),
    );
  }
}

但是,当characterName变量更改时,主类中图像的 JSON 路径会更改,但不会更新 ButtonAnimation 小部件中的路径。也就是说,如果将characterName设置characterName = "Jhon"为主类中图像的路径从 更改为assets/media/skill_icons/elise/elise_ability.pngassets/media/skill_icons/jhon/jhon_ability.png但给 ButtonAnimation 的路径仍为assets/media/skill_icons/elise/elise_ability.png。因此,我在考虑是否可以在主类中更新路径时更新 ButtonAnimation 中图像的路径。

标签: flutterflutter-desktopflutter-image

解决方案


推荐阅读