Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom image in a button in Flutter

Tags:

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

like image 333
Samyak Ranjan Avatar asked Jun 12 '17 10:06

Samyak Ranjan


People also ask

How do you add an icon to a button in Flutter?

The simplest way to create a button with icon and text in Flutter is to use the new Material button called ElevatedButton with an icon constructor. ElevatedButton. icon() gives you the ability to add the icon and label parameter to the button. The ElevatedButton was introduced with the release of Flutter v1.

How do I insert an image into an icon in Flutter?

To set the image to be displayed as the icon, you need to pass an ImageProvider instance. For that purpose, you need to create an instance of any class that's a descendant of ImageProvider such as AssetImage , NetworkImage , MemoryImage , and ResizeImage . The below example uses AssetImage to load the image.


1 Answers

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),
          ),
        ),
      ),
    );
  }
}
like image 120
Collin Jackson Avatar answered Sep 21 '22 10:09

Collin Jackson