Flutter入门报错:MyAppState未定义favorites getter求助
Flutter Codelab Step 6: Fix "The getter 'favorites' isn't defined" Error
问题说明
在完成《Your First Flutter App》第6步时,复制代码后出现构建错误:
The getter 'favorites' isn't defined for the type 'MyAppState'. Try importing the library that defines 'favorites', correcting the name to the name of an existing getter, or defining a getter or field named 'favorites'.
问题原因
你的MyAppState类未定义favorites收藏集合,也没有实现toggleFavorite的实际逻辑,但GeneratorPage中已经在尝试访问appState.favorites判断当前词对是否被收藏,导致属性未找到的错误。
解决方案
1. 完善MyAppState的收藏逻辑
修改MyAppState类,添加收藏集合并实现toggleFavorite方法:
class MyAppState extends ChangeNotifier { var current = WordPair.random(); // 新增收藏集合,用Set避免重复收藏 final favorites = <WordPair>{}; void getNext() { current = WordPair.random(); notifyListeners(); } void toggleFavorite() { if (favorites.contains(current)) { favorites.remove(current); } else { favorites.add(current); } notifyListeners(); // 通知UI更新状态 } }
2. 修复MyHomePage的导航状态管理
将MyHomePage改为StatefulWidget,实现导航栏切换页面的逻辑:
class MyHomePage extends StatefulWidget { @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int selectedIndex = 0; @override Widget build(BuildContext context) { Widget page; switch (selectedIndex) { case 0: page = GeneratorPage(); break; case 1: page = FavoritesPage(); break; default: throw UnimplementedError('no widget for $selectedIndex'); } return Scaffold( body: Row( children: [ SafeArea( child: NavigationRail( extended: false, destinations: [ NavigationRailDestination( icon: Icon(Icons.home), label: Text('Home'), ), NavigationRailDestination( icon: Icon(Icons.favorite), label: Text('Favorites'), ), ], selectedIndex: selectedIndex, onDestinationSelected: (value) { setState(() { selectedIndex = value; }); }, ), ), Expanded( child: Container( color: Theme.of(context).colorScheme.primaryContainer, child: page, ), ), ], ), ); } }
3. 添加收藏页面组件
新增FavoritesPage用于展示已收藏的词对:
class FavoritesPage extends StatelessWidget { @override Widget build(BuildContext context) { var appState = context.watch<MyAppState>(); if (appState.favorites.isEmpty) { return Center( child: Text('No favorites yet.'), ); } return ListView( children: [ Padding( padding: const EdgeInsets.all(20), child: Text('You have ${appState.favorites.length} favorites:'), ), for (var pair in appState.favorites) ListTile( leading: Icon(Icons.favorite), title: Text(pair.asLowerCase), ), ], ); } }
将以上修改整合到你的main.dart中,即可解决构建错误,实现两栏布局和收藏页面的核心功能。
内容的提问来源于stack exchange,提问作者radevpro
相关产品推荐
相关产品推荐

