周末找房快炸了,现在黑中介还是屡禁不止,继续敲代码吧,赚钱在每个城市都买个房子,虽然现在一个房子都没有,但梦想还是要有的。代码一定要比对好,因为写错一个地方有时候不会报错,但是错误很难查找。
第4步: 创建一个无限滚动ListView
在这一步中,您将扩展(继承)RandomWordsState类,以生成并显示单词对列表。 当用户滚动时,ListView中显示的列表将无限增长。 ListView的builder
工厂构造函数允许您按需建立一个懒加载的列表视图。
-
向RandomWordsState类中添加一个
_suggestions
列表以保存建议的单词对。 该变量以下划线(_)开头,在Dart语言中使用下划线前缀标识符,会强制其变成私有的。另外,添加一个
biggerFont
变量来增大字体大小class RandomWordsState extends State<RandomWords> { final _suggestions = <WordPair>[]; final _biggerFont = const TextStyle(fontSize: 18.0); ... }
-
向RandomWordsState类添加一个
_buildSuggestions()
函数. 此方法构建显示建议单词对的ListView。ListView类提供了一个builder属性,
itemBuilder
值是一个匿名回调函数, 接受两个参数- BuildContext和行迭代器i
。迭代器从0开始, 每调用一次该函数,i
就会自增1,对于每个建议的单词对都会执行一次。该模型允许建议的单词对列表在用户滚动时无限增长。添加如下高亮的行:
class RandomWordsState extends State<RandomWords> { ... Widget _buildSuggestions() { return new ListView.builder( padding: const EdgeInsets.all(16.0), // 对于每个建议的单词对都会调用一次itemBuilder,然后将单词对添加到ListTile行中 // 在偶数行,该函数会为单词对添加一个ListTile row. // 在奇数行,该函数会添加一个分割线widget,来分隔相邻的词对。 // 注意,在小屏幕上,分割线看起来可能比较吃力。 itemBuilder: (context, i) { // 在每一列之前,添加一个1像素高的分隔线widget if (i.isOdd) return new Divider(); // 语法 "i ~/ 2" 表示i除以2,但返回值是整形(向下取整),比如i为:1, 2, 3, 4, 5 // 时,结果为0, 1, 1, 2, 2, 这可以计算出ListView中减去分隔线后的实际单词对数量 final index = i ~/ 2; // 如果是建议列表中最后一个单词对 if (index >= _suggestions.length) { // ...接着再生成10个单词对,然后添加到建议列表 _suggestions.addAll(generateWordPairs().take(10)); } return _buildRow(_suggestions[index]); } ); } }
-
对于每一个单词对,
_buildSuggestions
函数都会调用一次_buildRow
。 这个函数在ListTile中显示每个新词对,这使您在下一步中可以生成更漂亮的显示行在RandomWordsState中添加一个
_buildRow
函数 :class RandomWordsState extends State<RandomWords> { ... Widget _buildRow(WordPair pair) { return new ListTile( title: new Text( pair.asPascalCase, style: _biggerFont, ), ); } }
-
更新RandomWordsState的build方法以使用
_buildSuggestions()
,而不是直接调用单词生成库。 更改后如下面高亮部分:class RandomWordsState extends State<RandomWords> { ... @override Widget build(BuildContext context) { final wordPair = new WordPair.random(); // 删除这两行 return new Text(wordPair.asPascalCase); return new Scaffold ( appBar: new AppBar( title: new Text('Startup Name Generator'), ), body: _buildSuggestions(), ); } ... }
-
更新MyApp的build方法。从MyApp中删除Scaffold和AppBar实例。 这些将由RandomWordsState管理,这使得用户在下一步中从一个屏幕导航到另一个屏幕时, 可以更轻松地更改导航栏中的的路由名称。
用下面高亮部分替换最初的build方法:
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Startup Name Generator', home: new RandomWords(), ); } }
重新启动应用程序。你应该看到一个单词对列表。尽可能地向下滚动,您将继续看到新的单词对。
遇到问题?
如果你的应用没有正常运行,你可以使用一下链接中的代码对比更正。
- lib/main.dart(https://gist.githubusercontent.com/Sfshaza/d6f9460a04d3a429eb6ac0b0f07da564/raw/34fe240f4122435c871bb737708ee0357741801c/main.dart)
这一块挺基础的,但是估计新学的需要费功夫,毕竟自己学,年纪也大了,哈哈,文章一篇篇发吧,这一块倒是没遇到什么问题,
注意:这个地方最容易出错的就是拼写错误,但是VSCode会在那个地方有提示,所以还好吧!