Hello how to add a sound while swiping left right in pageview I will add through gesture detector but the problem is that they will not judge the position left or right and if I will enable custom pageview scrolling then gesture detector does not work so how to do this


Solution 1: Shruti Ramnandan Sharma

for audio I used local audio (from assets) using audioplayers plugin.

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

class PageViewScreen extends StatefulWidget {
  @override
  _PageViewScreenState createState() => _PageViewScreenState();
}

class _PageViewScreenState extends State<PageViewScreen> {
  AudioCache _audioCache;

  final PageController _pageController = PageController(initialPage: 0);

  int staticIndex = 0;

  @override
  void initState() {
    super.initState();
    _audioCache = AudioCache(
      prefix: 'assets/audio/',
      fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    _audioCache.fixedPlayer.stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
          physics: ClampingScrollPhysics(),
          controller: _pageController,
          onPageChanged: (int page) {
            if (staticIndex < page + 1) {
              _audioCache.fixedPlayer.stop();

              _audioCache.play('next.wav');
              print("RIGHT SWIPE DETECTED ");
              setState(() => staticIndex++);
            } else {
              _audioCache.fixedPlayer.stop();
              _audioCache.play('previous.wav');
              print("LEFT SWIPE DETECTED");
              setState(() => staticIndex--);
            }
          },
          children: <Widget>[
            ChildClasss(
              title: "PAGE 1",
            ),
            ChildClasss(
              title: "PAGE 2",
            ),
            ChildClasss(
              title: "PAGE 3",
            ),
            ChildClasss(
              title: "PAGE 4",
            ),
            ChildClasss(
              title: "PAGE 5",
            ),
          ]),
    );
  }
}

class ChildClasss extends StatelessWidget {
  final String title;

  const ChildClasss({Key key, this.title}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Container(alignment: Alignment.center, child: Text(title));
  }
}