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;withfinal player = AudioCache();— the parentheses at the end tell Dart to initialize a new instance of theAudioCacheclass, 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
相关产品推荐
相关产品推荐

