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
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.
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.
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.
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),
),
),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With