flutter - 在 flutter 中动态分配图像

标签 flutter dart

如何在 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/

相关文章:

firebase - 有没有一种方法可以从Firebase在flutter应用程序中缓存音频文件

dart - 链式 future 不按顺序执行

google-maps - 如何在 flutter 中在谷歌地图上绘制多段线

video - 在 Flutter 中播放内联视频?

ios - Flutter iOS - MediaQuery.of(context).size.width 没有给出以像素为单位的宽度

Dart:如何将 '0' json 解码为 double

macos - 当我尝试在 iOS 模拟器上为我正在开发的应用程序运行我的 flutter 代码时,我收到 ERROR RUNNING POD INSTALL

dart - 可滚动的 flutter 弹出菜单

ios - 我可以在没有苹果开发者帐户的真实苹果设备上测试我的 Flutter 应用程序吗?如果可以,我该怎么做?

flutter - 如何监听字符串变量的变化并在发生变化时执行操作?