精讲Flutter官网的第一个例子


原文连接

前言

学习Flutter你必定会看到官网的第一个例子:中文版英文版。可是做为新手,或许你看的会很费劲,这篇文章的目的是帮助你更好的理解这个例子。android

最终的效果图:数组

最终效果

咱们先分析一下如何实现上图中的效果:app

Android开发者less

1. 准备数据:列表数据和选中的数据能够分别使用两个List或者数组存储。 2. 界面列表:使用ListView或RecyclerView 3. 界面跳转:可使用Intent携带数据到新的列表页

iOS开发者dom

1. 准备数据:列表数据和选中的数据能够分别使用两个数组存储。 2. 界面列表:使用TableView或CollectionView 3. 界面跳转:使用NavigationController,能够把值直接赋值给新的页面对象

结论

咱们发现,不管是原生的Android仍是iOS开发,都须要作的步骤是:ide

  1. 存储要展现的数据,存储选中的数据
  2. 展现列表,并把数据展现出来
  3. 设置跳转到新页面

因此在Flutter开发中,也遵守这几个步骤会更好的理解函数

Flutter开发工具

* 准备数据:列表数据使用数组存储,选中的数据可使用Set存储(由于set能够自动去重)。 * 界面列表:使用ListView * 界面跳转:可使用Navigator

拆解分析官方代码,带你快速理解

官网上使用大概110行代码实现上面的例子,咱们把这些代码拆解成主要的三部分来帮助咱们学习:学习

前提:你首先应该会用Android studio或者其余开发工具建立一个Flutter的工程,若是你须要学习关于这个步骤,能够在 这里快速学习开发工具

当你建立一个全新的Flutter工程并运行,界面上会出现熟悉的“Hello world”。 为了更容易的理解Flutter的代码,咱们先分析一下建立初始的代码,至少要知道咱们须要从哪里开始动手:

Snip20190104_19.png

咱们要编辑的就是这里的 main.dart 文件,跟其余语言同样,Flutter的入口函数是main函数:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());   //分析 1

class MyApp extends StatelessWidget {  //分析 2 (StatelessWidget)
  @override
  Widget build(BuildContext context) {   //分析 3
    return new MaterialApp(
      title: 'Welcome to Flutter',
      home: new Scaffold(      //分析 4
        appBar: new AppBar(
          title: new Text('Welcome to Flutter'),
        ),
        body: new Center(  //分析 5
          child: new Text('Hello World'),
        ),
      ),
    );
  }
}

复制代码

分析

  1. 这里的 => 是Dart中单行函数的简写,等价于:
void main() {
  runApp(new MyApp());
} 
复制代码
  1. StatelessWidget 表明只有一种状态的组件,与之对应的是StatefulWidget(表示可能有多种状态)。这里先不用深究其原理,只需知道这个跟flutter的刷新等相关。

  2. 在Widget组件中都是经过build方法来描述本身的内部结构。这里的build表示构建MyApp中使用的是MaterialApp的系统组件。

  3. home标签的值:Scaffold是Material library 中提供的一个组件,咱们能够在里面设置导航栏、标题和包含主屏幕widget树的body属性。能够看到这里是在页面上添加了AppBar和一个Text。

  4. Center是一个能够把子组件放在中心的组件

开始改造

咱们的目标是把页面中显示hello_world的TextView换成一个ListView。由上面的分析可知,将上面第4点的home标签的值,换成一个ListView就能改变页面显示的内容。不过在此以前,须要先准备一下要显示的数据,这里是使用一个叫 english_words 的三方包,能够帮助咱们生成显示的单词数据。先学习一下如何添加依赖包:

  1. 打开pubspec.yaml文件添加三方库:
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.0
  english_words: ^3.1.0
复制代码
  1. 点击 Packages get 获取刚添加的包。

添加english_words库以后,能够这样使用这个库创造数据:

//创造5个随机词组,并返回词组的迭代器
generateWordPairs().take(5)
复制代码

学习使用可变状态的组件 StatefulWidget

查看ListView的源码,发现其最终是继承自 StatelessWidget,因此它的状态是惟一的。可是要实现的ListView中的数据是动态变化的,因此须要使用StatefulWidget来动态改变ListView中的数据。

使用StatefulWidget组件须要本身控制在不一样状况下的显示状态,因此须要实现State类来告诉StatefulWidget类不一样状况下如何展现。

建立一个动态变化的组件类,用于表示要显示的ListView:

class RandomWords extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {  //分析1
    return new RandomWordsState();
  }
}
复制代码

分析:

  1. 建立State类的方法,这里继承系统的State创造一个名叫RandomWordsState的类,来控制ListView各个状态下的展现。
class RandomWordsState extends State<RandomWords> {
}
复制代码

要完成展现数据和保存点击后的数据,这里分别用数组和set来存储(用set存储点击后的数据是由于set能够去重,你也能够选择其余的存储方式)

class RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];   //分析 1
  final _saved = new Set<WordPair>();
  final _biggerFont = const TextStyle(fontSize: 18.0);   //分析 2
}
复制代码

分析:

  1. Dart中加上 _表示私有化
  2. 表示字体大小的常量

创造数据集和构建ListView

添加以下两个方法到RandomWordsState类中,表示创造数据集和构建ListView:

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]);
      }
    );
  }

  Widget _buildRow(WordPair pair) {
    final alreadySaved = _saved.contains(pair);

    return new ListTile(
      title: new Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: new Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }
复制代码

代码中有详细的注释,可是为了方便理解,这里仍是给出一点解释:

  1. _buildSuggestions方法就是返回一个ListView
  2. _buildRow方法就是返回ListView中的一行(ListTile)如何展现

_buildSuggestions方法中:

  • 代码中的itemBuilder就是如何显示一行(ListTile)的配置,其返回值是_buildRow方法
  • _suggestions.addAll(generateWordPairs().take(10));就是每次添加10个数据到显示数组中

_buildRow方法中:

  • 设置了一行(ListTile表明一行内容,在iOS和android中叫cell)如何展现
  • ListTile设置了title、trailing(右边的图标)和点击事件onTap()
  • 会根据有没有被保存过,决定右边显示什么图标
  • 当点击时,会把没有点击过的内容保存到_saved容器中。

添加跳转逻辑

添加_pushSaved方法表示如何跳转到新的页面并展现选中的数据:

main.dart

void _pushSaved() {
    Navigator.of(context).push(  // 分析 1
      new MaterialPageRoute(  // 分析 2
        builder: (context) {
          final tiles = _saved.map(  //数据
            (pair) {
              return new ListTile(
                title: new Text(
                  pair.asPascalCase,
                  style: _biggerFont,
                ),
              );
            },
          );
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();

          return new Scaffold(  // 分析 3
            appBar: new AppBar(
              title: new Text('Saved Suggestions'),
            ),
            body: new ListView(children: divided),
          );
        },
      ),
    );
  }
复制代码

分析: 1.使用Navigator.of(context).push的方式来处理跳转,须要的参数是一个Route 2.建立页面Route 3.返回一个新的里面,里面的body内容是一个ListView,展现的是_saved中读取出来的数据

最终,全部代码整合是以下的样子:

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Welcome to Flutter',
      theme: new ThemeData(
        primaryColor: Colors.red,
      ),
      home: RandomWords(),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new RandomWordsState();
  }
}

class RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _saved = new Set<WordPair>();
  final _biggerFont = const TextStyle(fontSize: 18.0);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Startup Name Generator'),
        actions: <Widget>[
          new IconButton(icon: new Icon(Icons.list), onPressed: _pushSaved),
        ],
      ),
      body: _buildSuggestions(),
    );
  }

  void _pushSaved() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          final tiles = _saved.map(
            (pair) {
              return new ListTile(
                title: new Text(
                  pair.asPascalCase,
                  style: _biggerFont,
                ),
              );
            },
          );
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();

          return new Scaffold(
            appBar: new AppBar(
              title: new Text('Saved Suggestions'),
            ),
            body: new ListView(children: divided),
          );
        },
      ),
    );
  }

  Widget _buildSuggestions() {
    return new ListView.builder(
        padding: const EdgeInsets.all(16.0),
        itemBuilder: (context, i) {
          if (i.isOdd) return new Divider();
          final index = i ~/ 2;
          if (index >= _suggestions.length) {
            _suggestions.addAll(generateWordPairs().take(10));
          }
          return _buildRow(_suggestions[index]);
        });
  }

  Widget _buildRow(WordPair pair) {
    final alreadySaved = _saved.contains(pair);

    return new ListTile(
      title: new Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: new Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }
}

复制代码

运行吧,就能看到最上方的效果。

谢谢观看这篇文章,若是让您发现了错误或者有好的建议,欢迎在下方评论给我留言。

相关文章
相关标签/搜索