'Custom image in a button in Flutter

I'm trying to create a button which will do some action when pressed, suppose it calls a function _pressedButton() also if the user taps on it (or taps and hold), the image changes.

Consider this like a button with a custom picture on pressed.

In the follow-up, can I also change the image based on some external factor? eg. if some function A returns true, show image 1, else show image 2



Solution 1:[1]

You can learn all about buttons and state in the Flutter interactivity tutorial.

For example, here is a button that shows a different cat every time each time it is clicked.

cat button

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  String _url = getNewCatUrl();

  static String getNewCatUrl() {
    return 'http://thecatapi.com/api/images/get?format=src&type=jpg&size=small'
           '#${new DateTime.now().millisecondsSinceEpoch}';
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Cat Button'),
      ),
      body: new Center(
        child: new FloatingActionButton(
          onPressed: () {
            setState(() {
              _url = getNewCatUrl();
            });
          },
          child: new ConstrainedBox(
            constraints: new BoxConstraints.expand(),
            child: new Image.network(_url, fit: BoxFit.cover, gaplessPlayback: true),
          ),
        ),
      ),
    );
  }
}

Solution 2:[2]

A handy way to achieve what you want is by using GestureDetector()

GestureDetector(
        onTap: () {
          //desired action command
        },
        child: Container(
          alignment: Alignment.center,
          width: 100,
          height: 100,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Image.asset('assets/icons/user.png'),
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(50),
            color: Colors.teal,
          ),
        ),
      ),

Result:

Result

GestureDetector() basically mimics a button.

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 Collin Jackson
Solution 2 MNBWorld