You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中AudioCache调用play方法报错:The method 'play' isn't defined for the type 'Type'

Flutter: The method 'play' isn't defined for the type 'Type' when using AudioCache

我在Flutter课程中跟着Angela编写的代码原本运行正常,但调用player.play('note1.wav')时无法正常工作,出现如下报错:

error: The method 'play' isn't defined for the type 'Type'. (undefined_method at [xylophone] lib/main.dart:17)

我的代码如下:

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

void main() => runApp(XylophoneApp());

class XylophoneApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: FlatButton(
              onPressed: () {
                final player = AudioCache;
                player.play('note1.wav');
              },
              child: Text('Click Me'),
            ),
          ),
        ),
      ),
    );
  }
}

Hey there, I spot the problem right away!

The core issue here is that you're assigning the AudioCache type itself to the player variable instead of creating an actual instance of the class. In Dart, writing final player = AudioCache; just stores a reference to the type, not an object you can call methods like play() on.

Quick Fix:

  • Replace final player = AudioCache; with final player = AudioCache(); — the parentheses at the end tell Dart to initialize a new instance of the AudioCache class, which gives you access to its methods.

Here's the corrected onPressed callback code:

onPressed: () {
  final player = AudioCache();
  player.play('note1.wav');
},

After making this change, your button should trigger the audio file playback without any errors!

内容的提问来源于stack exchange,提问作者Kyle Knoblauch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:42:34