I have a stack in a Flutter app, that stacks multiple images on top of each other. They are all of the same width and height, and have transparent backgrounds.
Individually, they look like this:
When they overlap, they look like this:
I need to make the visible part of each picture clickable. I do not want any interaction with the transparent part of any image. I've tried using GestureDetector, but since all the images are of the same size, it isn't working too well. How do I achieve this?
Circle the borders of the picture in any vector graphics editor, I used figma.com, it's free.
Save it as svg file, open it and copy path from svg.
Convert svg paths to Flutter Paths, I've used the path_drawing package.
Use custom clipper to clip image by path.
Unfortunately, path_drawing package ignores the beginning of the path. So you need to add it, by adding offset.
Add GestureDetector.
import 'package:flutter/material.dart';
import 'package:path_drawing/path_drawing.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: SafeArea(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String clicked = '';
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
_getClippedImage(
clipper: _Clipper(
svgPath: svgCarPath,
offset: Offset(66, 157),
),
image: 'assets/image.png',
onClick: _handleClick('car'),
),
_getClippedImage(
clipper: _Clipper(
svgPath: svgManPath,
offset: Offset(115, 53),
),
image: 'assets/image.png',
onClick: _handleClick('man'),
),
Positioned(
child: Text(
clicked,
style: TextStyle(fontSize: 30),
),
bottom: 0,
),
],
);
}
void Function() _handleClick(String clickedImage) {
return () => setState(() {
clicked = clickedImage;
});
}
Widget _getClippedImage({
_Clipper clipper,
String image,
void Function() onClick,
}) {
return ClipPath(
clipper: clipper,
child: GestureDetector(
onTap: onClick,
child: Image.asset('assets/image.png'),
),
);
}
}
class _Clipper extends CustomClipper<Path> {
_Clipper({this.svgPath, this.offset = Offset.zero});
String svgPath;
Offset offset;
#override
Path getClip(Size size) {
var path = parseSvgPathData(svgPath);
return path.shift(offset);
}
#override
bool shouldReclip(CustomClipper oldClipper) {
return false;
}
}
const svgCarPath =
'M35 13.7742L46.9628 1.52606L58.8398 5.97996V17.1147L111.544 13.7742L117.111 50.8899L109.688 55.715C108.575 61.2823 103.75 72.417 93.3574 72.417C82.965 72.417 80.4751 64.3753 80.4751 59.4266C68.1032 55.5913 53.5355 53.8592 39.5397 57.5708C35.0128 76.8252 14.4397 76.0591 12.0741 55.715H0.939362V26.7647L12.0741 17.1147L35.8281 13.7742Z';
const svgManPath =
'M50.2647 19.9617C50.6461 5.85163 47.5952 0.703364 38.2521 0.703369C32.0776 2.87051 31.0217 6.36354 30.625 14.0016C30.625 14.0016 27.9555 28.1424 30.625 32.8584C33.2945 37.5744 42.1784 35.788 39.3961 40.7456C36.6138 45.7032 27.9555 63.6268 27.9555 63.6268H22.6165C14.7864 70.572 19.1843 79.9011 12.1293 88.7962C3.01255 100.291 -0.77319 103.733 0.879345 106.911L8.12508 109.199L19.1844 96.8046L12.1293 120.258L15.9428 123.499L22.6165 121.402L32.7224 97.9487L39.3961 104.622C36.5995 110.597 32.2267 122.088 37.108 120.258C43.2097 117.97 54.2865 120.258 66.0909 113.394C75.3267 28.4915 49.8834 34.0719 50.2647 19.9617Z';
Related
I'm currently making a 3-slides long Intro Slider for my application, using the Flutter package intro_slider.
Everything works flawlessly and looks perfect, but since I decided to use a custom png image as my backgroundImage, it seems that the package shows the image with extremely darker colors.
In the image I've attached I'm showing the effective problem. The one on top (using centerWidget to show it) is the expected image that should show with the exact same colors.
On the back there is the backgroundImage, darkened automatically.
I couldn't find anyone else talking about this issue and hope someone found a way to "solve" it.
Is there a way to stop the darkening of the image?
Thanks in advance.
I have currently tried:
Changing image extensions and trying again.
Remove everything but the backgroundImage (I thought that the image was darkened because of the items on top of it)
Here is the code I wrote for the slides:
Main
void main() {
runApp(const MyApp());
}
// Main
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Goals App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: IntroScreen(),
);
}
}
IntroScreen
class IntroScreen extends StatefulWidget {
const IntroScreen({Key? key}) : super(key: key);
#override
IntroScreenState createState() => IntroScreenState();
}
class IntroScreenState extends State<IntroScreen> {
List<Slide> slides = [];
#override
void initState() {
super.initState();
slides.add(Slide(
backgroundImage: 'assets/images/intro_first_slide.png',
centerWidget:
Image(image: AssetImage('assets/images/intro_first_slide.png')),
));
}
Widget renderNextBtn() {
return const Icon(
Icons.navigate_next,
color: Colors.white,
size: 35.0,
);
}
Widget renderDoneBtn() {
return const Icon(
Icons.done,
color: Colors.white,
size: 35.0,
);
}
Widget renderSkipBtn() {
return const Icon(
Icons.skip_next,
color: Colors.white,
size: 35.0,
);
}
#override
Widget build(BuildContext context) {
return IntroSlider(
// List Slides
slides: slides,
// Skip button
// renderSkipBtn: renderSkipBtn(),
// Next button
renderNextBtn: renderNextBtn(),
// Done button
renderDoneBtn: renderDoneBtn(),
// Dot indicator
colorDot: Colors.white,
colorActiveDot: Colors.grey[300],
sizeDot: 13.0,
// show/hide status bar
hideStatusBar: true,
backgroundColorAllSlides: Colors.grey,
// Scrollbar
verticalScrollbarBehavior: scrollbarBehavior.HIDE,
);
}
}
Maybe this is what you are looking for?
https://pub.dev/packages/intro_slider#slide-object-properties all the way down at the bottom of the properties list:
backgroundBlendMode BlendMode? BlendMode.darken Background tab image filter blend mode
probably like so
slides.add(
Slide(
backgroundImage: 'assets/images/intro_first_slide.png',
centerWidget: Image(
image: AssetImage('assets/images/intro_first_slide.png'),
),
backgroundBlendMode: BlendMode.srcOver // <- try this
),);
I am using following code to display image as splash screen :
class WelcomeWidget extends StatefulWidget {
static const routeName = '/welcome_page';
#override
_WelcomeWidgetState createState() => _WelcomeWidgetState();
}
class _WelcomeWidgetState extends State<WelcomeWidget> {
#override
void initState() {
super.initState();
Timer(
Duration(seconds: 10),
() => Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => LowerStripWidget(),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:
Container(
child:Center(
child: Image.asset('assets/images/Splash-Screen-bg.png'),
),
width: double.infinity,
),
);
}
}
This shows the image but does not stretch image to fill the white space.
How we can do that in flutter?
Here is the current screen:
You can use the fit property of the Image widget to determine how to inscribe the image into the space allocated during layout.
I added an example using your code:
Image.asset(
'assets/images/Splash-Screen-bg.png',
// set the fit property to cover
it: BoxFit.cover, // new line
),
If two containers completely overlap each other in stack then how do we detect onTap() event on bottom when widget at top is clicked?
Use Case:
My top container is transparent. I am using this transparent container tap to animate top widgets (this top widget sticks at the bottom of the sceen). And on tap I want to animate same bottom element at position.
Additianly I implemented custom Rawgesture but i don't see gesture arena conflicts. This arena conflicts are only detected if elements are positioned such that one is parent and second is child.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(children: <Widget>[
GestureDetector(
onTap: () {
print('green clicked.');
},
child: Container(
color: Colors.green,
width: 400,
height: 400,
),
),
GestureDetector(
onTap: () {
print('red clicked.');
},
child: Container(
color: Colors.red,
width: 200,
height: 200,
),
),
]),
);
}
}
In this above example When I click on red container it will print red clicked but there is some part of green container is also present. I want to know if both events can be called?
Thanks.
AFAIK, there is no direct way to know if there is an underlying widget where user has tapped. However, I ran your code of red and green containers and achieved it with onTapDown event
Simplest solution (without onTapDown) ::
Added a following function :
void onGreenClick()
{
print("Green clicked");
}
Changed Green's onTap handler as :
onTap: onGreenClick,
And added onGreenClick() in Red's onTap as :
onTap: () {
print('red clicked.');
onGreenClick();
},
However, as you guess this will work only when the widgets are completely overlap on each other. In case, there's some area where red container is present but not green then above would fail. To, achieve that, you use onTapDown as below :
Add onTapDown handler to both red and green (under GestureDetector) as :
onTapDown: (TapDownDetails details) => onTapDown(context, details),
where the handler function is :
void onTapDown(BuildContext context, TapDownDetails details) {
print('${details.globalPosition}');
final RenderBox box = context.findRenderObject();
final Offset localOffset = box.globalToLocal(details.globalPosition);
setState(() {
posx = localOffset.dx;
posy = localOffset.dy;
});
if (posx < 100.0 && posy < 100.0) onGreenClick();
}
Now, if you see the last line, we call onGreenClick only on the specific x,y-coordinates.
Thus the end result is you get "Green click" in the debug output window even on clicking on red.
The entire code is available here
I'm trying to restart an animated gif on Flutter. The gif image loads from network without a problem and animates after loading. I need to restart the animation on tapping a button.
Tried so far:
- setState
- change Key to some other unique key and setState to rebuild.
Solution as #chemamolins 's suggestion:
int _robotReloadCount=0;
....
GestureDetector(
onTap: () {
onTapRobot();
},
child: Center(
child: Container(
margin: EdgeInsets.only(top: 55.0, bottom: 5.0),
height: 150.0,
width: 150.0,
child:
FadeInImage(
key: this._robotImageKey,
placeholder: AssetImage('assets/common/robot_placeholder.png'),
image: NetworkImage(snapshot.data['robot_image_path'] +"robot_level" +snapshot.data['robot_level'].toString() +".gif"+"?"+this._robotReloadCount.toString()))),
),
),
....
onTapRobot() async{
setState(() {
this._robotReloadCount++;
});
}
I have done a lot of tests and it is not easy. The image is cached by the 'ImageProvider' and whatever you change or no matter the times you invoke build() the image is loaded from what is available in the cache.
So, apparently, you only have two options.
Either you rebuild with a new url, for instance by appending #whatever to the image url.
Or you remove the image from the cache as shown in the code below.
In either case you need to fetch again the image from the network.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String url = "https://media.giphy.com/media/hIfDZ869b7EHu/giphy.gif";
void _evictImage() {
final NetworkImage provider = NetworkImage(url);
provider.evict().then<void>((bool success) {
if (success) debugPrint('removed image!');
});
setState(() {});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: Image.network(url),
),
floatingActionButton: new FloatingActionButton(
onPressed: _evictImage,
child: new Icon(Icons.remove),
),
);
}
}
I have written a Flutter application that makes use of package:flutter/material.dart. Running the app on the iOS Simulator looks as follows. As you can see, there is no padding between components in one row, and the components reach to top, bottom, left and right without padding/margin/border. My question is:
What is the recommended way to apply Material-compliant padding, for example for the label-component-gap between Convert to and the dropdown button. Would I pack my components in a Container and apply padding there?
Thank you very much in advance.
This is the application code:
import 'package:flutter/material.dart';
import 'converter.dart';
import 'model.dart';
const _appName = 'Temperature Converter';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: _appName,
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: _appName),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Model model = new Model();
var _currentInput = const InputValue();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(config.title),
),
body: new Column(children: <Widget>[
new Row(children: <Widget>[
new Expanded(
child: new Input(
hintText: 'Temperature',
value: _currentInput,
onChanged: (input) => _currentInput = input)),
new DropdownButton(
items: createUnit(),
onChanged: (temperatureUnit newValue) {
setState(() {
model.inUnit = newValue;
});
},
value: model.inUnit)
]),
new Row(children: <Widget>[
new Text("Convert to"),
new DropdownButton(
items: createUnit(),
onChanged: (temperatureUnit newValue) {
setState(() {
model.outUnit = newValue;
});
},
value: model.outUnit),
]),
new FlatButton(
child: new Text('Calculate'),
onPressed: () {
setState(() {
double inTemp = stringToDouble(_currentInput.text);
model.inTemperature = inTemp;
model.calculateOutTemperature();
});
}),
new Text(model.outTemperatureAsString)
]), // This trailing comma tells the Dart formatter to use
// a style that looks nicer for build methods.
);
}
List<DropdownMenuItem> createUnit() {
var l = new List<DropdownMenuItem<temperatureUnit>>();
// degrees Celsius
l.add(new DropdownMenuItem<temperatureUnit>(
value: temperatureUnit.degreesCelsius,
child: new Text(unitDegreesCelsius)));
// degrees Fahrenheit
l.add(new DropdownMenuItem<temperatureUnit>(
value: temperatureUnit.degreesFahrenheit,
child: new Text(unitDegreesFahrenheit)));
// Kelvin
l.add(new DropdownMenuItem<temperatureUnit>(
value: temperatureUnit.kelvin, child: new Text(unitKelvin)));
return l;
}
}
The question is by no means implying that Flutter is missing something. I merely want to do it right. ;-)
Generally I would recommend using a Block as the child of the Scaffold. It has a padding value that you can set.
You can also just use a Padding widget.
I only know ButtonTheme that have a padding value
ButtonTheme.of(context).padding
So I think the best solution for now is to have constant value and use a Container to apply your padding.
Maybe I am wrong but I don't know any Widget that automatically apply any Material padding.