1

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

Please help me.

**NOW THE IMAGE APPEARS AND DISAPPEARS WHEN THE BUTTON IS PRESSED. But it don't refreshes to get a new one (it's a dynamic URL)

***Now the image change when it is pressed, but I don't 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 reducing or increasing the image so it can fit perfectly, but it didn't work.

Also, the URL is 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

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
  • Have a look at [this](https://stackoverflow.com/questions/68735657/how-to-display-an-image-when-user-click-on-button-flutter) – princesanjivy Mar 31 '22 at 18:29
  • how do you want to show the image? as a po-up or underneath the button? – MCB Mar 31 '22 at 19:02
  • could you expand further on what exactly you want? ie navigate to anothr page and display it, or a modalbottom that comes up to display? also show what code you have so far. – flutterloop Mar 31 '22 at 19:11
  • Thanks for the questions I'm going to upload my code. I want in the same page to have a button and when I press it show a image from the website in a column above the button. – Bruno Franco Sentis Mar 31 '22 at 21:10

1 Answers1

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,
         ),
    
Samia Ashraf
  • 195
  • 5
  • Thanks I'm going to try this. In your code you didn't especified the bool variable, if you can do it more in detail I will be very happy. Thanks for your time and effort I really appreciate it. – Bruno Franco Sentis Apr 01 '22 at 12:31
  • add `bool showImage = false;` before the build method, since you will change the value inside setState later. – Samia Ashraf Apr 01 '22 at 12:53
  • Thank you very much for your time, I'm going to test it in the afternoon – Bruno Franco Sentis Apr 01 '22 at 13:02
  • Please accept the answer if it works for you so that it can benefit others in future. – Samia Ashraf Apr 01 '22 at 14:40
  • Hey Samia thank you very much, it work almost perfect. I wanna add a container so the image fit it, but it didint work for me. Also i wanna know how make that when i press the button the showImage turn false again so i can, press again and generate a new image (its a dynamic url). Again thanks you so much. Im going to update my code in the post. Hope you can help me. – Bruno Franco Sentis Apr 01 '22 at 14:55
  • Im thinking to created an int value = 0; and a function with if value.isEven then showImage = false, else its true, and when the button its press the value of the int, increase. It work, but the image dosent change. And i dont know how to add to a container. – Bruno Franco Sentis Apr 01 '22 at 15:43
  • https://stackoverflow.com/questions/65890460/flutter-refresh-network-image I find this method. – Bruno Franco Sentis Apr 01 '22 at 16:29
  • Modify the setState from `showImage = true;` to `showImage = !showImage;` – Samia Ashraf Apr 02 '22 at 15:49
  • thanks i just update the code. thanks for your help. i accepted your answer. – Bruno Franco Sentis Apr 02 '22 at 16:56