问题描述
按下时,每个容器都会发出声音。
我已经通过使函数playSound缩短了它。但是有没有办法使它更短?
queue = []
最后,我想提到我使用textButton,因为flatButton等已经过时了。谢谢。
解决方法
我看到您的TextButtons非常相似,因此您可以创建一个无状态对象,该对象返回具有相似属性和不同颜色以及onPressed方法的TextButton!
class MyTextButton extends StatelessWidget {
final color;
final onPressed;
const MyTextButton({
Key key,this.color,this.onPressed,}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(
EdgeInsets.fromLTRB(0,0)),),onPressed: () {
this.onPressed;
},child: Container(
height: 80,width: 90,color: this.color,);
}
}
并像这样使用MyButton
而不是TextButton
:
import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
void main() => runApp(XylophoneApp());
class XylophoneApp extends StatelessWidget {
void playSound(int soundNumber) {
final player = AudioCache();
player.play('note$soundNumber.wav');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
children: [
MyTextButton(
color: Color(0xffFF80AB),onPressed: () {
playSound(1);
},MyTextButton(
color: Color(0xffFF80AB),MyTextButton(...),],);
}
}
,
您可以为窗口小部件创建一个类,并向其传递索引参数以选择颜色和声音,并使用ListView.builder
创建每个窗口小部件,例如以下代码:
class Test2 extends StatefulWidget {
@override
_Test2State createState() => _Test2State();
}
class _Test2State extends State<Test2> {
int selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,itemCount: 7,itemBuilder: (BuildContext context,int index) {
return CustomButtonWidget(
index: index,);
}),));
}
}
class CustomButtonWidget extends StatelessWidget {
final int index;
CustomButtonWidget({this.index});
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(
EdgeInsets.fromLTRB(0,onPressed: () {
playSound(index + 1);
},color: index.isEven ? Color(0xffFF80AB) : Color(0xff880E4F),);
}
}
,
是的,您可以使用ListView.builder
将其缩短。看起来如下:
ListView.builder(
itemCount: 7,itemBuilder: (ctx,index) => TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all<EdgeInsets>(
EdgeInsets.fromLTRB(0,onPressed: () {
playSound(index + 1);
},child: Container(
height: 80,color: index % 2 == 0 ? Color(0xffFF80AB) : Color(0xff880E4F),
基本上,您在itemBuilder
中循环了7次并返回了TextButton
。您正在使用索引来确定颜色和传递给playSound
的值。
如果遇到Expanded
错误,则可能需要将ListView包装在Vertical viewport was given unbounded height.
小部件中。