I have a main screen named "ItemsScreen". inside of this has a listview.builder. I have a widget named "ItemCard" for creating listview items.
Problem – I want to stop audio when a user navigates between different screens in my flutter app.
- One navigation has inside of ItemCard
- Other navigation has main screen.
If any time, User navigate to any screen, I want to stop audio If it is playing.
I’m using audioplayers: ^5.1.0
package. – link
ItemsScreen like this:
class _YourWidgetState extends State<YourWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 3,
itemBuilder: (context, index) {
return ItemCard(
audioUrl: 'audio_url_for_YourWidget');
},
),
//navigate to setting screen
floatingActionButton: FloatingActionButton(
onPressed: () {
// ------------------------------------------------ navigation
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SettingScreen(),
),
);
},
child: Icon(Icons.settings),
),
);
}
}
ItemCard like this:
class ItemCard extends StatefulWidget {
final String audioUrl;
ItemCard({
required this.audioUrl,
});
@override
_ItemCardState createState() => _ItemCardState();
}
class _ItemCardState extends State<ItemCard> {
bool isPlaying = false;
void _loadAudio() async {
if (!isPlaying) {
setState(() {
loading = true;
isStarted = true;
});
await audioPlayer.play(
UrlSource(
'https://firebasestorage.googleapis.com/v0/b/voice-feed.appspot.com/o/audio%2F1694248558321?alt=media&token=20194024-0060-43e5-b66c-dd10ec4537a0'),
);
setState(() {
loading = false;
});
} else {
await audioPlayer.pause();
}
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
ElevatedButton(
onPressed: _loadAudio,
child: Text(isPlaying ? 'Pause' : 'Play'),
),
// ------------------------------------------------ navigation
ElevatedButton(
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ItemViewScreen(),
),
);
}
child: Text('View the item'),
),
],
),
);
}
}
2
Answers
Finally, find a way to do this task.
For this you have to define a audio player outside of any class or function like this
Then whenever you navigate to screen you can have a init method, that will be called as soon as screen is called and then you can play, pause or stop the audio
So on your main screen that is item screen you can have it like this
You can apply it in same way in another screen.
And don’t forget to import the player from where you have defined it. Also don’t dispose the player, after disposing it you will not be able to play any thing on it