简体   繁体   中英

How to make reusable widget in flutter card swiper?

I'm attempting to use the Flutter Swiper with different parameters on the same page, however I'm unsure how to structure the code.

I want this same code in Multiple Pages I was tried several way but it doesn't work. So I want make this Widget as Reusable

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,
  );
}

create a new dart class and create a custom widget that you can use anywhere in your application like below (dont forget to import 'package:flutter/material.dart';" in cutom swiper class)

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(),
  ),
);
}

Now use customSwiper as you use other Flutter Material widget anywhere in the application and you can add parameter according to your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM