Reputation: 83
I'm a beginner in flutter and I'm looking for a simple way to refresh a network image.
In a basic code like this, what would be the simplest method of getting flutter to fetch and draw this image again? In my code the image is a snapshot from a security camera, so it changes every time it is fetched, but always has the same url. I get a new picture every time I start the app, but I would like the image refreshed when I press the image itself.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var title = 'Web Images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Image.network('https://picsum.photos/250?image=9'),
),
);
}
}
Upvotes: 7
Views: 7824
Reputation: 29
Another tricky solution is to add a dummy argument which changes every time, then the image will be treat as different image source and will refresh image every time when you access it. For example add t=currentTimestamp, but you don't need handle this argument in the web server.
ex: Image.network('https://picsum.photos/250?image=9?t=${DateTime.now().millisecond}'
Upvotes: 2
Reputation: 101
If you need forced picture refresh - try such code:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var title = 'Web Images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ForcePicRefresh(),
));
}
}
class ForcePicRefresh extends StatefulWidget {
@override
_ForcePicRefreshState createState() => _ForcePicRefreshState();
}
class _ForcePicRefreshState extends State<ForcePicRefresh> {
String url =
'https://www.booths.co.uk/wp-content/uploads/British-Flower-1x1-2-660x371.jpg';
Widget _pic;
@override
void initState() {
_pic = Image.network(url);
super.initState();
}
_updateImgWidget() async {
setState(() {
_pic = CircularProgressIndicator();
});
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
.buffer
.asUint8List();
setState(() {
_pic = Image.memory(bytes);
});
}
@override
Widget build(BuildContext context) {
return InkWell(
child: _pic,
onTap: () {
_updateImgWidget();
},
);
}
}
Upvotes: 2