Home > Net >  How to click the button in flutter to change the background image
How to click the button in flutter to change the background image

Time:09-17

I am a beginner in flutter, I don’t understand the concept of Widget very well.

I want to set the background image as an unsplash random image, but I want to add a button to request a random image again when I click it, but I am confused about many concepts of Flutter, and I don’t know how to complete this function.

Below is my current code, I don’t know how to change it, please help me, thank you very much!

import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        title: 'Welcome to Flutter',
        theme: new ThemeData(
          brightness: Brightness.light,
      ),
        home: new Scaffold(
          appBar: new AppBar(
            title: new Text("Welcome to Flutter"),
          ),
          body: BackgroundImgDemo()
        ),
    );
  }
}

class BackgroundImgDemo extends StatelessWidget {
  final String imgUrl="https://unsplash.it/1440/3040?random";
  const BackgroundImgDemo({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: new DecorationImage(
          fit: BoxFit.cover,
          image: new NetworkImage(imgUrl),
        ),
      ),
      child: Container(
        margin: EdgeInsets.only(top: 500.0),
        child: Center(
          child: RaisedButton(
            color: Colors.white,
            child: Text("clicke here!"),
            onPressed: () {
              
            },
          )
        ),
      ),
    );
  }
}


CodePudding user response:

I'm also a very beginner and I attempted to solve your problem. My approach was to

  1. change your stateless widget to stateful widget
  2. Used a NetworkImage variable showImg to pass to the image widget
  3. create a function updateUI that will refresh the image to show
  4. called updateUI from onPressed function

But this doesn't seem to be working as well. Following the thread to know how to do it

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'Welcome to Flutter',
      theme: new ThemeData(
        brightness: Brightness.light,
      ),
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text("Welcome to Flutter"),
          ),
          body: BackgroundImgDemo()),
    );
  }
}

class BackgroundImgDemo extends StatefulWidget {
  @override
  State<BackgroundImgDemo> createState() => _BackgroundImgDemoState();
}

class _BackgroundImgDemoState extends State<BackgroundImgDemo> {
  final String imgUrl = "https://unsplash.it/1440/3040?random";
  NetworkImage showImg = NetworkImage("https://unsplash.it/1440/3040?random");

  void updateUI() {
    setState(() {
      showImg = NetworkImage(imgUrl);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.cover,
          image: showImg,
        ),
      ),
      child: Container(
        margin: EdgeInsets.only(top: 500.0),
        child: Center(
          child: RaisedButton(
            color: Colors.white,
            child: const Text("click here!"),
            onPressed: () => updateUI(),
          ),
        ),
      ),
    );
  }
}


CodePudding user response:

Firstly, you need to use StatefulWidget to make any changes over UI. But here the second issue is image is loading from cache after 1st load being the same URL.

As long you use the same URL within context, images will load from cache. about the upspash URL you can tweak some value by adding something at the end of URL on button pressed.

Here is the widget


class MyWidgetsBinding extends WidgetsFlutterBinding {
  @override
  ImageCache createImageCache() => MyImageCache();
}

class _BackgroundImgDemoState extends State<BackgroundImgDemo> {
  String imgUrl1 = "https://unsplash.it/1440/3040?random";

  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: new DecorationImage(
          fit: BoxFit.cover,
          image: new NetworkImage(
            "${imgUrl1}$count",
          ),
        ),
      ),
      child: Container(
        margin: EdgeInsets.only(top: 500.0),
        child: Center(
            child: RaisedButton(
          color: Colors.white,
          child: Text("clicke here!"),
          onPressed: () async {
            print("clear cache");
            setState(() {
              count  ;
            });
          },
        )),
      ),
    );
  }
}

You can also try cached_network_image to maintain cache.

  • Related