美文网首页Flutter 实战
Flutter入门(4):编写Flutter程序

Flutter入门(4):编写Flutter程序

作者: Maojunhao | 来源:发表于2020-09-02 09:25 被阅读0次

    1. 编写 Flutter 程序

    下文是按照官方文档随便体验一下,有兴趣直接开始Flutter编程的可以点这里

    2. 创建 flutter App

    创建一个flutter App,可以参考创建流程

    3. 运行 App

    flutter run

    4. 编辑第一个 Hello world程序

    删除 main.dart 文件内容,复制粘贴以下代码,保存后刷新模拟器,可以参考flutter基本操作

    import 'package:flutter/material.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Welcome to Flutter',
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text('Welcome to Flutter'),
            ),
            body: new Center(
              child: new Text('Hello World'),
            ),
          ),
        );
      }
    }
    

    5. 使用 Package

    导入english_words的开源软件包 ,其中包含数千个最常用的英文单词以及一些实用功能.
    首先打开App目录下 pubspec.yaml 文件,在 dependencies 下新增 english_words

    dependencies:
      flutter:
        sdk: flutter
    
      cupertino_icons: ^0.1.0
      english_words: ^3.1.0
    

    保存后,运行以下命令安装

    flutter pub get

    安装完成后,重新启动模拟器

    flutter run

    在 main.dart 文件中导入头文件,并修改部分代码,如下

    import 'package:flutter/material.dart';
    import 'package:english_words/english_words.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            final wordPair = new WordPair.random();
            return new MaterialApp (
                title : 'Welcome',
                home : new Scaffold(
                    appBar: new AppBar( title: new Text('Welcome to Flutter') ), 
                    body : new Center(child: new Text(wordPair.asPascalCase)),
                ),
            );
        }
    }
    

    保存后,刷新模拟器


    simulator.png

    6. 添加一个 Stateful widget (标记状态的组件)

    复制粘贴以下代码至 main.dart ,具体组件功能后续文章再做讲解。
    运行后与之前效果完全相同,只不过是将 Text(wordPair.asPascalCase) 生成的随机单词换成 RandomWords() 生成的随机单词。

    import 'package:flutter/material.dart';
    import 'package:english_words/english_words.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return new MaterialApp (
                title : 'Welcome',
                home : new Scaffold(
                    appBar: new AppBar( title: new Text('Welcome to Flutter') ), 
                    body : new Center(child: new RandomWords()),
                ),
            );
        }
    }
    
    class RandomWords extends StatefulWidget {
        @override
        createState() => new RandomWordsState();
    }
    
    class RandomWordsState extends State <RandomWords> {
        @override
        Widget build(BuildContext context) {
            final wordPair = new WordPair.random();
            return new Text(wordPair.asPascalCase);
        }
    }
    
    

    7. 创建一个 ListView (TableView)

    import 'package:flutter/material.dart';
    import 'package:english_words/english_words.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return new MaterialApp (
                title : 'Welcome',
                home : new RandomWords(),
            );
        }
    }
    
    class RandomWords extends StatefulWidget {
        @override
        createState() => new RandomWordsState();
    }
    
    class RandomWordsState extends State <RandomWords> {
        @override
        final _suggestions = <WordPair>[];
        final _biggerFont = const TextStyle(fontSize : 18.0);
        Widget build(BuildContext context) {
            return new Scaffold(
                appBar: new AppBar(title: new Text('ListView')),
                body: _buildSuggestions(),
                );
        }
        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) {
            return new ListTile(
                title : new Text(
                    pair.asPascalCase,
                    style: _biggerFont,
                )
            );
        }
    }
    

    运行后如下


    simulator_listview.png

    8. 添加 ListView 的点击事件,并对点击状态进行保存

    import 'package:flutter/material.dart';
    import 'package:english_words/english_words.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return new MaterialApp (
                title : 'Welcome',
                home : new RandomWords(),
            );
        }
    }
    
    class RandomWords extends StatefulWidget {
        @override
        createState() => new RandomWordsState();
    }
    
    class RandomWordsState extends State <RandomWords> {
        @override
        final _suggestions = <WordPair>[];
        final _saved = new Set<WordPair>();
        final _biggerFont = const TextStyle(fontSize : 18.0);
        Widget build(BuildContext context) {
            return new Scaffold(
                appBar: new AppBar(title: new Text('ListView')),
                body: _buildSuggestions(),
                );
        }
        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);
                        }
                    });
                },
            );
        }
    }
    

    运行刷新后如下


    simulator_state.png

    9. 通过路由实现 flutter 的页面跳转

    import 'package:flutter/material.dart';
    import 'package:english_words/english_words.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return new MaterialApp (
                title : 'Welcome',
                home : new RandomWords(),
            );
        }
    }
    
    class RandomWords extends StatefulWidget {
        @override
        createState() => new RandomWordsState();
    }
    
    class RandomWordsState extends State <RandomWords> {
        @override
        final _suggestions = <WordPair>[];
        final _saved = new Set<WordPair>();
        final _biggerFont = const TextStyle(fontSize : 18.0);
        Widget build(BuildContext context) {
            return new Scaffold(
                appBar: new AppBar(title: new Text('ListView'),
                    actions: <Widget>[
                    new IconButton(icon: new Icon(Icons.list), onPressed: _pushSaved),
                    ],
                ),
                body: _buildSuggestions(),
            );
        }
        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);
                        }
                    });
                },
            );
        }
        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),
                        );
                    },
                ),
            );
        }
    }
    

    保存运行后如图


    simulator_route_home.png
    simulator_route_push.png

    10. 更改主题色

    通过 ThemeData 类来改变主题色,修改以下部分代码

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

    保存运行后如下图


    simulator_route_home_white.png
    simulator_route_push_white.png

    11. 小结

    本文到这里就结束了,全部代码均为跟着官方教程走了一遍。主要就以下几个功能点

    • ListView 的创建
    • ListView 的Item状态及保存
    • Item 的状态保存及按照不同的状态刷新UI
    • Route 的页面跳转及回跳
    • 主题色的修改

    相关文章

      网友评论

        本文标题:Flutter入门(4):编写Flutter程序

        本文链接:https://www.haomeiwen.com/subject/swmcsktx.html