我能够使用在扩展 State 的类中创建的方法,因此希望在其他类中使用相同的方法来正常工作。
方法:
await tts.setVolume(1);
await tts.setSpeechRate(0.5);
await tts.setPitch(1);
if (app.txt != null) {
if (app.txt!.isNotEmpty) {
await tts.speak(app.txt!);
}
}
}
由于扩展 State 类的类是私有的,不知道我应该做什么...
class _AppState extends State<App>{...}
你能帮忙吗?
我已经创建了基类的实例:
app.speak();
遇到一个错误:未为“App”类型定义“speak”方法。
如上所述,speak方法属于_AppState的类,尽管它是私有的......
你可以做这样的事情
class AppState extends StatefulWidget {
const AppState({super.key});
@override
State<AppState> createState() => AppStateState();
}
class AppStateState extends State<AppState> {
Future<void> speak() async {
return;
}
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
class AnotherWidget extends StatefulWidget {
const AnotherWidget({super.key});
@override
State<AnotherWidget> createState() => _AnotherWidgetState();
}
class _AnotherWidgetState extends State<AnotherWidget> {
void anotherMethod(BuildContext context) {
final ttf = context.findAncestorStateOfType<AppStateState>();
ttf?.speak();
}
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
注意
AnotherWidget
是顶部 AppState 的子级。
void anotherMethod(BuildContext context) {
final ttf = context.findAncestorStateOfType<AppStateState>();
ttf?.speak();
}