【问题标题】:How to make reusable widget in flutter card swiper?如何在颤动卡刷卡器中制作可重复使用的小部件?
【发布时间】:2021-07-14 10:22:50
【问题描述】:

我正在尝试在同一页面上使用具有不同参数的 Flutter Swiper,但是我不确定如何构造代码。

我想在多个页面中使用相同的代码我尝试了几种方法,但它不起作用。 所以我想让这个 Widget 可重用

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

【问题讨论】:

    标签: flutter flutter-layout flutter-dependencies flutter-slider flutter-audio-query


    【解决方案1】:

    创建一个新的 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 小部件一样,您可以根据需要添加参数。

    【讨论】:

    • playaudio() in index bro
    • 你能详细说明你的查询吗
    猜你喜欢
    • 2020-04-12
    • 2021-09-29
    • 1970-01-01
    • 2020-09-06
    • 2020-08-11
    • 2021-11-20
    • 2020-02-25
    • 2020-01-14
    • 2020-04-29
    相关资源
    最近更新 更多