'Flutter button to display image above it

Hello everyone I hope yall good. I want to know how to create a button and when it get pressed display an image and a column or row.

Please help me.

**NOW THE IMAGE APPEARS AND DISSAPEARS WHEN THE BUTTON ITS PRESSED. But it dont refresh to get a new one (its a dynamic url)

***Now the image change when it pressed, but i dont know where i can put the button.

UPDATE CODE 5.0

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'colors.dart';

const String url = 'http://thecatapi.com/api/images/get?format=src&type=gif';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme:
            ThemeData(primarySwatch: primaryBlack, accentColor: Colors.white),
        debugShowCheckedModeBanner: false,
        home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late Uint8List bytes;
  bool loading = true;

  @override
  void didChangeDependencies() async {
    getBytes();
    super.didChangeDependencies();
  }

  void getBytes() async {
    setState(() {
      loading = true;
    });

    Uint8List newbytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
        .buffer
        .asUint8List();

    setState(() {
      bytes = newbytes;
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              ':(:',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text('FelizTriste'),
            Text(':(:', style: TextStyle(fontWeight: FontWeight.bold)),
          ],
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            loading
                ? const SizedBox(
                    width: 355,
                    height: 355,
                    child: Center(child: CircularProgressIndicator()))
                : Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: primaryBlack, width: 6)),
                    child: Image.memory(
                      bytes,
                      width: 350,
                      height: 350,
                      fit: BoxFit.cover,
                    ),
                  ),
            SizedBox(
              height: 60,
            ),
            ElevatedButton(onPressed: getBytes, child: const Text('GATIT@S')),
            const Text(
              '¿Quieres ver gatit@s?',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            )
          ],
        ),
      ),
    );
  }
}

I tried to add a Container, for the purpose of reduce or increase the image so it can fit perfect, but i didnt work.

Also, the url its a dynamic one, so i want to "refresh" the image display with each button hope you can help me.

Going to learn this method: Flutter: refresh network image



Solution 1:[1]

I have modified your code:

  1. removed image function, instead create a variable, bool showImage which should be false initially.

  2. When the button is pressed, showImage should be changed to true.

     ElevatedButton(
       onPressed: () {
         setState(() {
           showImage = true;
         });
       },
       child: Text('GATIT@S')
    ),
    
  3. The image and text should only be displayed when showImage variable is true, otherwise display empty SizedBox().

     showImage
       ? Column(
           children: [
             Image.network(           'https://docs.flutter.dev/assets/images/dash/dash-fainting.gif'),
             Text('Hola')
           ],
         )
       : SizedBox(
           height: 0,
         ),
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samia Ashraf