我发现在 React Native 中,在使用组件时,按相应的区域会产生不透明度效果。在颤振中,我们当然可以使用 InkWell 小部件,但我不想要矩形或正方形。我们可以使用颤振实现相同的结果吗?干杯!
使用以下代码:
import 'package:flutter/material.dart';
class TouchableOpacity extends StatefulWidget {
final Widget child;
final Function onTap;
final Duration duration = const Duration(milliseconds: 50);
final double opacity = 0.5;
TouchableOpacity({@required this.child, this.onTap});
@override
_TouchableOpacityState createState() => _TouchableOpacityState();
}
class _TouchableOpacityState extends State<TouchableOpacity> {
bool isDown;
@override
void initState() {
super.initState();
setState(() => isDown = false);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => setState(() => isDown = true),
onTapUp: (_) => setState(() => isDown = false),
onTapCancel: () => setState(() => isDown = false),
onTap: widget.onTap,
child: AnimatedOpacity(
child: widget.child,
duration: widget.duration,
opacity: isDown ? widget.opacity : 1,
),
);
}
}
用法:
TouchableOpacity(
child: ....
onTap: () {....}
)
@Shan刘你说得对,InkWell有自己的"飞溅"效果,可以形成你提到的矩形或正方形。
如果您不想要这种飞溅效果,请使用手势检测器。
在下面的例子中,我把一个文本放在一个手势检测器中,但你可以把你的小部件放在那里:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'InkWell Demo';
return MaterialApp(
title: title,
home: MyHomePage(title: title),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(child: MyButton()),
);
}
}
class MyButton extends StatefulWidget {
@override
MyButtonState createState() {
return MyButtonState();
}
}
class MyButtonState extends State<MyButton> {
bool isTappedDown = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
},
onTapDown: (tapDownDetails) {
setState(() {
isTappedDown = true;
});
},
onTapUp: (tapUpDetails) {
setState(() {
isTappedDown = false;
});
},
child: Text(
'Flat Button',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: isTappedDown ? Colors.black.withOpacity(0.5) : Colors.black),
),
);
}
}
我认为
您需要结合手势检测器和不透明度动画。我找不到现成的示例。但这里是不透明度动画的示例。颤振不透明度动画
这是我
创建的可触摸类。(您可以在此处轻松添加透明度)
class Touchable extends StatelessWidget {
final Widget child;
final Function() onPress;
final double borderRadius;
final double padding;
const Touchable(
{Key key, this.child, this.onPress, this.borderRadius, this.padding})
: super(key: key);
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(borderRadius),
child: Material(
color: Colors.transparent,
child: InkWell(
child: Padding(
padding: EdgeInsets.all(padding),
child: child,
),
onTap: this.onPress),
),
);
}
}