我正试图在同一页面上使用具有不同参数的FlutterSwiper
,但我不确定如何构建代码。
我想在多页中使用相同的代码,我尝试过几种方法,但都不起作用。所以我想让这个小工具成为可重复使用的
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
class Animals extends StatefulWidget {
@override
_AnimalsState createState() => _AnimalsState();
}
class _AnimalsState extends State<Animals> {
List images = [
'assets/images/img/getStart.jpg',
'assets/images/a/a.jpg',
'assets/images/a/b.jpg',
'assets/images/a/c.jpg',
'assets/images/a/d.jpg',
'assets/images/a/e.jpg',
'assets/images/a/f.jpg'
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animals'),
),
body: Swiper(
itemCount: images.length,
loop: false,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(27.0),
child: Image.asset(
images[index],
),
);
},
indicatorLayout: PageIndicatorLayout.COLOR,
onIndexChanged: (index) {
playaudio(index);
},
autoplayDelay: 10000,
autoplay: true,
pagination: SwiperPagination(),
control: SwiperControl(),
),
);
}
}
void playaudio(index) async {
AssetsAudioPlayer.newPlayer().open(
Audio('assets/audio/a/a$index.mp3'),
autoStart: true,
loopMode: LoopMode.none,
showNotification: true,
);
}
创建一个新的dart类,并创建一个自定义小部件,您可以在应用程序中的任何地方使用,如下所示(不要忘记在cutom-swiper类中导入"package:flutter/material.dart";"(
Widget customSwiper({List image }){
return Swiper(
itemCount: images.length,
loop: false,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(27.0),
child: Image.asset(
images[index],
),
);
},
indicatorLayout: PageIndicatorLayout.COLOR,
onIndexChanged: (index) {
playaudio(index);
},
autoplayDelay: 10000,
autoplay: true,
pagination: SwiperPagination(),
control: SwiperControl(),
),
);
}
现在使用customSwiper就像您在应用程序中的任何地方使用其他Flutter Material小部件一样,您可以根据需要添加参数。