Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

Flutter: refresh network image

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'),
      ),
    );
  }
} 
question from:https://stackoverflow.com/questions/65890460/flutter-refresh-network-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
      },
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...