Flutter制作自己的第一个全平台APP学习之Widgets篇

已收录   阅读次数: 946
2021-06-2015:32:53 发表评论
摘要

伯衡君这一个月正在学习Flutter这门编程语言以制作自己的一个Android和iOS以及Web端的全平台App,感觉入门相对来说未找到捷径,那么姑且做些笔记来整理思路,把复杂的事情分解成一个个简单的内容,以达成最终的目的,所以伯衡君准备将Flutter按照各个部件来拆分学习,想到此前学习Web开发时,也是先html,css,javascript这些开始学习的,为了提高效率,缩短学习时间,毕竟人生短暂,必须有另外一番捷径可循,让我们开始吧……

分享至:
Flutter制作自己的第一个全平台APP学习之Widgets篇

开篇寄语

伯衡君这一个月正在学习Flutter这门编程语言以制作自己的一个Android和iOS以及Web端的全平台App,感觉入门相对来说未找到捷径,那么姑且做些笔记来整理思路,把复杂的事情分解成一个个简单的内容,以达成最终的目的,所以伯衡君准备将Flutter按照各个部件来拆分学习,想到此前学习Web开发时,也是先html,css,javascript这些开始学习的,为了提高效率,缩短学习时间,毕竟人生短暂,必须有另外一番捷径可循,让我们开始吧。

前情提要

内容详情

以下内容大多是更改lib下的main.dart文件内容,删掉里面的内容,复制粘贴代码,开启调试就可以出现了

Icon

  • 是指一些小图标,这在美化页面,丰富内容上起到很大作用,而在Flutter中设置也非常简单,内置了很多Icon图标,只需要输入相应的代码进行调用就可以了,以下面的例子来说
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Welcome to Flutter',
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: Center(
            child: Icon(
              Icons.bluetooth,
              color: Theme.of(context).primaryColor,
              size: 32.0,
            ),
          ),
        ));
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

其中Icons.bluetooth是中间的蓝牙标志,在Flutter的库中,有庞大的图标可以使用,详情请点此移步到官方图标库:

比如Icons.favorite就是心形的图案,总之,各种内置的图标非常多,足够在大部分情况使用。

Text

  • Flutter中的文字,可以输出任何内容,进行样式的设置,如下所示:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Welcome to Flutter',
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: Center(
              child: const Text('Hello World',
                  style: TextStyle(
                      color: Color(0xFFFF0000),
                      backgroundColor: Colors.yellow,
                      fontSize: 42.0,
                      fontStyle: FontStyle.italic,
                      decoration: TextDecoration.underline))),
        ));
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

更多有关Text的样式设置,以及方法的使用,则可移步到官网的这个页面:

TextField

  • 该组件多是用户输入内容,包括输入用户名,密码,评论之类的,试举例如下:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: Center(
              child: Container(
                  width: 400.0,
                  child: TextField(
                    keyboardType: TextInputType.name,
                    style: Theme.of(context).textTheme.headline5,
                    maxLength: 36,
                    decoration: InputDecoration(
                      icon: const Icon(Icons.people),
                      labelText: 'Please enter a user name',
                      // ignore: dead_code
                      errorText: true ? null : 'Please enter your name',
                    ),
                  )))),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

另外的一种用于评论或者撰写多行文本的输入框,示例如下:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: Center(
              child: Container(
            width: 400.0,
            child: TextField(
              maxLines: 5,
            ),
          ))),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

TextFormField

  • 相当于一个表格,填写信息,比如用户名,密码登陆,试举例如下:
/// Flutter code sample for TextFormField

// This example shows how to move the focus to the next field when the user
// presses the SPACE key.

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

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: Shortcuts(
          shortcuts: const <ShortcutActivator, Intent>{
            // Pressing space in the field will now move to the next field.
            SingleActivator(LogicalKeyboardKey.space): NextFocusIntent(),
          },
          child: FocusTraversalGroup(
            child: Form(
              autovalidateMode: AutovalidateMode.always,
              onChanged: () {
                Form.of(primaryFocus!.context!)!.save();
              },
              child: Wrap(
                children: List<Widget>.generate(4, (int index) {
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ConstrainedBox(
                      constraints: BoxConstraints.tight(const Size(200, 50)),
                      child: TextFormField(
                        onSaved: (String? value) {
                          print('Value for field $index saved as "$value"');
                        },
                      ),
                    ),
                  );
                }),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

Image

  • 图片,Flutter设置图片也是十分简单,而且形式多样,试举例如下:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Welcome to Flutter'),
          ),
          body: Center(
              child: Container(
                  width: 400.0,
                  child: const Image(
                    image: NetworkImage(
                        'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
                  )))),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇
  • 或者在本地引用也可以,试举例如下:

首先是在项目目录内创建一个新的文件夹,取名为assets,伯衡君根据个人需要会在该文件夹下面新建一个文件夹名为images,如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

接下来是修改pubspec.yaml文件,其中有一段代码是修改图片索引的:

flutter:
  assets:
      - assets/images/

这样设置是设置为索引文件夹assets/images内的所有图片。

接下来就是修改main.dart文件,试举例如下:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root
  // of your application

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Insert Image Demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Image.asset('images/dartside.png'),
            ],
          ),
        ),
      ),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

Card

  • 该组件类似于卡片,矩形,正方形等等,总之是一个可以让应用整齐美观的重要组件,试举例如下:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root
  // of your application

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Insert Image Demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Card(
                color: Colors.green,
                margin: const EdgeInsets.all(20.0),
                elevation: 0.0,
                child: SizedBox(
                  height: 100.0,
                  child: InkWell(
                    splashColor: Colors.deepOrange,
                    onTap: () {
                      print('Clicked!');
                    },
                    child: Row(
                      children: const <Widget>[
                        Expanded(
                          child: Text('Card'),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

简单来说,就是生成的卡片点击后会有颜色改变,同时在调试窗口生成点击的记录。

Gradient

  • 这个是一种渐变色,能够让页面看起来更加炫酷,也让色彩搭配更加多变,试举例如下:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root
  // of your application

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Insert Image Demo'),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Colors.red.shade400,
                  Colors.blue.shade400,
                  Colors.yellow
                ],
                stops: [0.25, 0.5, 1.0],
              ),
            ),
          ),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Card(
                color: Colors.green,
                margin: const EdgeInsets.all(20.0),
                elevation: 0.0,
                child: SizedBox(
                  height: 100.0,
                  child: InkWell(
                    splashColor: Colors.deepOrange,
                    onTap: () {
                      print('Clicked!');
                    },
                    child: Row(
                      children: const <Widget>[
                        Expanded(
                            child: Center(
                          child: Text('Card'),
                        )),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

Button

  • 一看就是各种按钮啦,菜单按钮,选择按钮等等,这个涉及的种类比较多,一个个举例学习。

TextButton

  • 简单的按钮实现,试举例如下:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter Buttons - FlatButton'),
          ),
          body: Center(
              child: Column(children: <Widget>[
            Container(
              margin: EdgeInsets.all(25),
              child: TextButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.red)),
                child: Text(
                  'Button 2',
                  style:
                      TextStyle(fontSize: 20.0, color: Colors.yellow.shade200),
                ),
                onPressed: () {
                  print("Clicked!");
                },
              ),
            ),
          ]))),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

ElevatedButton

  • 简单来说是一个带有边界的按钮,比textButton豪华一些,试举例如下:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Flutter Buttons - FlatButton'),
          ),
          body: Center(
              child: Column(children: <Widget>[
            Container(
              width: 200.0,
              height: 50.0,
              margin: EdgeInsets.all(25),
              child: ElevatedButton(
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.red)),
                child: Text(
                  'Button 2',
                  style:
                      TextStyle(fontSize: 20.0, color: Colors.yellow.shade200),
                ),
                onPressed: () {
                  print("Clicked!");
                },
              ),
            ),
          ]))),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

OutlinedButton

  • 带有外边的按钮,加了一层装饰而已,类似于TextButton

PopupMenuButton

  • 此常用于右上角弹出菜单,以供选择,试举例如下:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Menu'),
            actions: [
              PopupMenuButton<int>(
                key: _key,
                itemBuilder: (context) {
                  return <PopupMenuEntry<int>>[
                    PopupMenuItem(child: Text('0'), value: 0),
                    PopupMenuItem(child: Text('1'), value: 1),
                  ];
                },
              ),
            ],
          ),
          body: Center(
              child: Column(children: <Widget>[
            Container(
              width: 200.0,
              height: 50.0,
              margin: EdgeInsets.all(25),
              child: OutlinedButton(
                child: Text(
                  'Button 2',
                  style:
                      TextStyle(fontSize: 20.0, color: Colors.yellow.shade200),
                ),
                onPressed: () {
                  print("Clicked!");
                },
              ),
            ),
          ]))),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

MaterialButton

  • 用于构建依赖于环境 ButtonTheme 和 Theme 的 Material 按钮的实用程序类,这个可以制作圆形的按钮等,试举一例:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Buttons - FlatButton'),
        ),
        body: Center(
          child: MaterialButton(
            color: Colors.blue,
            shape: CircleBorder(),
            onPressed: () {},
            child: Padding(
              padding: const EdgeInsets.all(100),
              child: Text(
                'A circle button',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

生成效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

SwitchListTile

  • 一种切换按钮,可以快速切换状态,试举一例:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey();
  bool _lights = false;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Menu'),
            actions: [
              PopupMenuButton<int>(
                key: _key,
                itemBuilder: (context) {
                  return <PopupMenuEntry<int>>[
                    PopupMenuItem(child: Text('0'), value: 0),
                    PopupMenuItem(child: Text('1'), value: 1),
                  ];
                },
              ),
            ],
          ),
          body: Center(
              child: SwitchListTile(
            title: const Text('Lights'),
            value: _lights,
            onChanged: (bool value) {
              setState(() {
                _lights = value;
              });
            },
            secondary: const Icon(Icons.lightbulb_outline),
          ))),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

CheckBox

  • 是一种多选按钮,试举例如下:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<PopupMenuButtonState<int>> _key = GlobalKey();
  bool isChecked = false;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Menu'),
            actions: [
              PopupMenuButton<int>(
                key: _key,
                itemBuilder: (context) {
                  return <PopupMenuEntry<int>>[
                    PopupMenuItem(child: Text('0'), value: 0),
                    PopupMenuItem(child: Text('1'), value: 1),
                  ];
                },
              ),
            ],
          ),
          body: Center(
              child: Checkbox(
            checkColor: Colors.white,
            fillColor: MaterialStateProperty.all(Colors.amber),
            value: isChecked,
            onChanged: (bool? value) {
              setState(() {
                isChecked = value!;
              });
            },
          ))),
    );
  }
}

生成的效果如下图所示:

Flutter制作自己的第一个全平台APP学习之Widgets篇

还有更多的按钮,可以参看官网的这个分页:

ArrayArrayArray
  • 我的微信
  • 微信扫一扫加好友
  • weinxin
  • 我的微信公众号
  • 扫描关注公众号
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: