flutter music keeps playing when I stop playing song with function and change navigation bar index flutter music keeps playing when I stop playing song with function and change navigation bar index dart dart

flutter music keeps playing when I stop playing song with function and change navigation bar index


add: "with WidgetsBindingObserver"

class Screen extends StatefulWidget with WidgetsBindingObserver

and you'll get access to the App Lifecycle State:

void didChangeAppLifecycleState(AppLifecycleState state) {    if (state == AppLifecycleState.paused) {      player.pause();    }  }


It sounds like you're trying to build a carousel slider. I would suggest instead of trying to build it you use something like the carousel_slider package. You should be able to just call play in the callback for onPageChanged.

However, getting back to your specific issue, I think the issue is that you're likely getting the page index and the globalSongIndex out of sync.

It seems like you have something like this globally:

  var audioIndex = 0;  var audioFiles = [    "1.mp3",    "2.mp3",    "3.mp3"  ];

with a play function like this:

  Future<void> play() async {    int result = await audioPlayer.play(audioFiles[audioIndex]);  }

Then to ensure your gesture and your pageView on your pageView controller are in sync you need to make sure when you call the nextPage function on the PageController you also ensure your state variable is also updated to the nextPage value. I'm not exactly sure on how the specifics of Provider.of<Songs> works, but you likely need to force it to a specific value.

SliverChildBuilderDelegate((ctx, pageIndex) => GestureDetector(    onPanUpdate: (details) async {      if (details.delta.dx < 0) {        _controller.nextPage(            duration: Duration(milliseconds: 200),            curve: Curves.easeInOut);        await stop();        setState(() {          audioIndex = pageIndex;          play();        });      }    },    child: Center(child: Text(audioFiles[audioIndex])))

Full working example:

import 'package:audioplayers/audioplayers.dart';import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';void main() {  runApp(MyApp());}class MyApp extends StatelessWidget {  // This widget is the root of your application.  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(        primarySwatch: Colors.blue,      ),      home: MyHomePage(title: 'Flutter Demo Home Page'),    );  }}class MyHomePage extends StatefulWidget {  MyHomePage({Key key, this.title}) : super(key: key);  final String title;  @override  _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  var audioPlayer = AudioPlayer(playerId: 'player');  var audioIndex = 0;  var audioFiles = [    "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",    "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",    "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"  ];  var _controller = PageController();  @override  void initState() {    super.initState();// starting player    startPlayer();  }  startPlayer() {    play();  }// Player play class set globalindex  Future<void> play() async {    int result = await audioPlayer.play(audioFiles[audioIndex]);    if (result == 1) {      // success    }  }  // Stop song instance of player  Future<void> stop() async {    int result = await audioPlayer.stop();    if (result == 1) {      // success    }  }  // disposing listener if not needed or users navigates away from  @override  void dispose() {    super.dispose();    audioPlayer.dispose();  }  @override  Widget build(BuildContext context) {    return Scaffold(        appBar: AppBar(          title: Text(widget.title),        ),        body: PageView.custom(            dragStartBehavior: DragStartBehavior.start,            controller: _controller,            physics: NeverScrollableScrollPhysics(),            scrollDirection: Axis.horizontal,            childrenDelegate:                SliverChildBuilderDelegate((ctx, pageIndex) => GestureDetector(                    onPanUpdate: (details) async {                      if (details.delta.dx < 0) {                        _controller.nextPage(                            duration: Duration(milliseconds: 200),                            curve: Curves.easeInOut);                        await stop();                        setState(() {                          audioIndex = pageIndex;                          play();                        });                      }                    },                    child: Center(child: Text(audioFiles[audioIndex]))))));  }}