我有一个 Flutter 应用程序。有多个按钮、手势检测器、文本按钮等。我需要为它们每个添加一个按钮声音,而不需要一一修改。我认为这可以通过光线投射实现,但我无法实现它。是否可以在不指定按钮的确切坐标的情况下使用光线投射?示例代码将受到高度赞赏。
我尝试了 usibg 重铸,但似乎我需要使用按钮的确切位置。
是的,您可以在 Flutter 中使用 Raycasting 来实现按钮音效,而无需指定按钮的确切坐标。光线投射可用于检测其区域内的任何小部件何时发生触摸事件。以下是如何实现此功能的基本示例:
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
final AudioCache _audioCache = AudioCache();
void _playButtonSound() {
// Play button sound
_audioCache.play('button_sound.mp3');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Button Sound Example'),
),
body: GestureDetector(
onTapDown: (details) {
// Play button sound when any part of the screen is tapped
_playButtonSound();
},
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
onPressed: () {
// Your button's onPressed logic
},
child: Text('FlatButton'),
),
GestureDetector(
onTap: () {
// Your GestureDetector's onTap logic
},
child: Container(
padding: EdgeInsets.all(12),
color: Colors.blue,
child: Text('GestureDetector'),
),
),
TextButton(
onPressed: () {
// Your TextButton's onPressed logic
},
child: Text('TextButton'),
),
],
),
),
),
);
}
}
您只需将“button_sound.mp3”替换为按钮声音文件的实际路径即可。