教程:https://codelabs.developers.google.com/codelabs/first-flutter-app-pt2

1.添加收藏图标

  1. class RandomWordsState extends State<RandomWords> {
  2. // Set 元组不允许重复元素,不同于 List
  3. final Set<WordPair> _saved = Set<WordPair>();
  4. ...
  5. Widget _buildRow(WordPair pair) {
  6. // 添加 _saved 状态
  7. final bool alreadySaved = _saved.contains(pair);
  8. return ListTile(
  9. ...
  10. // 添加 icon
  11. trailing: Icon(
  12. alreadySaved ? Icons.favorite : Icons.favorite_border,
  13. color: alreadySaved ? Colors.red : null,
  14. ),
  15. );
  16. }
  17. ...
  18. }

2.添加收藏交互效果

  1. class RandomWordsState extends State<RandomWords> {
  2. ...
  3. Widget _buildRow(WordPair pair) {
  4. ...
  5. return ListTile(
  6. ...
  7. // 添加点击事件,通过增加删除 _saved 中对应 pair 元素来达到切换效果
  8. onTap: () {
  9. // setState 之后会重新 build 组件
  10. setState(() {
  11. if (alreadySaved) {
  12. _saved.remove(pair);
  13. } else {
  14. _saved.add(pair);
  15. }
  16. });
  17. },
  18. );
  19. }
  20. ...
  21. }

效果图

image.png

3.导航到新页面

APP顶栏添加一个按钮和点击事件。

  1. Widget build(BuildContext context) {
  2. return Scaffold(
  3. appBar: AppBar(
  4. title: Text('单词本'),
  5. // 添加一个动作组件 IconButton,列表按钮,按下的事件是 _pushSaved
  6. actions: <Widget>[
  7. IconButton(icon: Icon(Icons.list), onPressed: _pushSaved),
  8. ],
  9. ),
  10. body: _buildSuggestions()
  11. );
  12. }
  13. void _pushSaved() {
  14. // 导航切换视图
  15. Navigator.of(context).push(
  16. MaterialPageRoute<void>(
  17. builder: (BuildContext context) {
  18. final Iterable<ListTile> tiles = _saved.map(
  19. (WordPair pair) {
  20. return ListTile(
  21. title: Text(
  22. pair.asPascalCase,
  23. style: _biggerFont,
  24. ),
  25. );
  26. },
  27. );
  28. final List<Widget> divided = ListTile
  29. .divideTiles(
  30. context: context,
  31. tiles: tiles,
  32. )
  33. .toList();
  34. return Scaffold(
  35. appBar: AppBar(
  36. title: Text('Saved Suggestions'),
  37. ),
  38. body: ListView(children: divided),
  39. );
  40. },
  41. ),
  42. );
  43. }

image.pngimage.png
右侧图片展示的就是跳转到新的导航页面,收藏夹页面展示我们收藏的单词。
请注意,导航器会在应用顶栏中添加“后退”按钮。我们不必显式实现Navigator.pop。点击后退按钮就可以返回到主路线。

4.修改顶栏颜色

  1. class MyApp extends StatelessWidget {
  2. // 应用的根组件
  3. @override
  4. Widget build(BuildContext context) {
  5. return MaterialApp(
  6. title: '欢迎使用新青柚天气',
  7. theme: ThemeData(
  8. primarySwatch: Colors.teal,
  9. ),
  10. home: RandomWords(),
  11. );
  12. }
  13. }

image.pngimage.png

Tips

  1. 某些窗口小部件属性采用单个窗口小部件(子窗口)child,而其他属性(如操作)则采用窗口小部件(子窗口)数组children,如方括号([])所示。

本次提交代码

https://github.com/youngchou1997/flutter_app/commit/a742225bb156fd4945f22de24cc8b82823975f20