Flutter 中的背景音乐不起作用

Background music in Flutter does not work

我正在尝试将背景音乐添加到我的应用程序中。如果我启动我的应用程序,音乐会正确开始,但如果我按下一个对音乐没有影响的按钮,音乐会从新开始。我在 Flutter.Here 中的代码是我的代码 我把不重要的东西删掉了。

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';


class _MyHomepageState extends State<MyHomepage> {
  AudioPlayer player = AudioPlayer();
  AudioCache cache = new AudioCache();
  bool isPlaying = false;

  Future<bool> _willPopCallback() async {
    if (isPlaying == false) {
      setState(() {
        isPlaying = true;
      });
      player.stop();
    }
    return true;
  }

  openingActions() async {
    player = await cache.loop('audio/test.mp3');
  }

 
  @override
  Widget build(BuildContext context) {
    openingActions();
    return WillPopScope(
        onWillPop: () => _willPopCallback(),
        child: Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/background.jpg'),
                fit: BoxFit.cover,
              ),
            ),
    ...
    ...
    ...
raisedbutton(
....
)


您可以复制粘贴运行下面的完整代码
您可以将 openingActions();build 移动到 initState
而且rebuild不会再调用openingActions();

@override
  void initState() {
    openingActions();
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    //openingActions(); //delete this line and move to initState

完整代码

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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> {
  AudioPlayer player = AudioPlayer();
  AudioCache cache = new AudioCache();
  bool isPlaying = false;

  Future<bool> _willPopCallback() async {
    if (isPlaying == false) {
      setState(() {
        isPlaying = true;
      });
      player.stop();
    }
    return true;
  }

  openingActions() async {
    player = await cache.loop('audio/test.mp3');
  }

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    openingActions();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Open route'),
              onPressed: () {
                setState(() {});
              },
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}