Skip to content

Instantly share code, notes, and snippets.

@KrzysztofLen
Last active March 19, 2022 07:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
This is the source code of the Flutter Challenges series post: https://fun4code.com/10flutterchallanges-part3/
import 'package:audioplayers/audioplayers.dart';
abstract class AudioService {
static AudioCache audioCache = AudioCache();
static AudioPlayer audioPlayer = AudioPlayer(
playerId: 'my_unique_playerId',
mode: PlayerMode.LOW_LATENCY,
);
static void play(String filename) async {
audioPlayer = await audioCache.play(filename);
}
static void stop() async => await audioPlayer.stop();
}
import 'package:flutter/material.dart';
import 'package:samples/audio_service/audio_service.dart';
class LifeCycleService extends StatefulWidget {
final Widget child;
const LifeCycleService({Key? key, required this.child}) : super(key: key);
@override
_LifeCycleServicerState createState() => _LifeCycleServiceState();
}
class _LifeCycleServiceState extends State<LifeCycleService>
with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance!.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance!.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
AudioService.play('music/track_01.mp3');
break;
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
AudioService.stop();
break;
}
}
@override
Widget build(BuildContext context) {
return Container(
child: widget.child,
);
}
}
import 'package:flutter/material.dart';
import 'package:samples/audio_service/audio_service.dart';
import 'package:samples/lifecycle_widget.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
AudioService.play('music/track_01.mp3');
return const LifeCycleService(
child: MaterialApp(
home: Scaffold(
body: Text('App'),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment