颤振 - 当 URL 未更改时重新加载网络图像所需的内容



我刚刚开始学习Flutter的应用程序开发。

我正在尝试构建一个用于学习的应用程序,该应用程序使用API从网站获取图像以获得随机图像。该应用程序显示图像,并有一个按钮,当按下时,该按钮将获取一个新的随机图像。

问题是API的URL没有改变,所以Flutter认为图像是一样的,并没有下载新的图像。至少,这是我认为正在发生的事情。

代码非常基本。到目前为止,只显示了一个图像和一个按钮。我试过各种方法,认为按下按钮时imageCache.clear();应该完成任务,但似乎什么都不起作用。我还尝试了各种重置状态的技巧,并尝试使用命名路由导航到同一页面,但它们仍然显示相同的图像(这就是为什么我认为这可能是缓存问题(:耸耸肩:

所有这些都是从一个main.dart文件中运行的。

import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.lightGreen[50],
appBar: AppBar(
title: Text("Show Me The Lettuce",
style: TextStyle(color: Colors.white70)),
backgroundColor: Colors.green[900],
),
body: ShowLettuce(),
),
),
);
}
class ShowLettuce extends StatefulWidget {
@override
_ShowLettuceState createState() => _ShowLettuceState();
}
class _ShowLettuceState extends State<ShowLettuce> {
String url = 'https://source.unsplash.com/900x900/?lettuce';
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(80.0),
child: Center(child: CircularProgressIndicator()),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage, image: url),
),
],
),
SizedBox(
height: 20.0,
),
RaisedButton(
onPressed: () {
imageCache.clear();
print('button pressed.');
},
child: Text('Show Me A New Lettuce!'),
),
],
),
);
}
}

我已经阅读了很多Flutter文档,但我还没有到可以将它们所说的大部分内容解释为可用代码的地步(不确定我应该在哪里以及如何将其插入我的代码中,例如imageCache文档:https://api.flutter.dev/flutter/painting/ImageCache-class.html)。这似乎应该是一个非常简单的解决方案,但它正在逃离我

非常感谢您的帮助。

我已经解决了你的问题。

你必须为你的代码添加几行代码:

作为第一个-导入:

import 'dart:math';

next-在类_ShowLettuceState中声明的url变量之后:

var random = new Random();

和完成-点击按钮后,即在按下:

setState(() {   
url = 'https://source.unsplash.com/900x900/?lettuce' + random.nextInt(100).toString();
});

我建议您使用以下代码:

String url = 'https://source.unsplash.com/900x900/?lettuce-${Random().nextInt(100)}';

这是受@Captivaty解决方案的启发,但我添加了一个-使其发挥作用。

最新更新