Flutter学习(六)基础Widget

2020-04-09  本文已影响0人  yanhooIT

Android Studio开发快捷键

Command(⌘)、Shift(⇧)、Option(⌥)、Control(⌃)、Return/Enter(↩︎)

如何使用一个陌生的Widget

文本Widget

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Text"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      color: Colors.green,
      alignment: Alignment.center,
      child: Text(
        "《定风波》 苏轼 \n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。",
        // 所有内容都居中对齐
        textAlign: TextAlign.center,
        // 最多显示三行
        maxLines: 3,
        // 超出部分显示...
        overflow: TextOverflow.ellipsis,
        // 文本缩放比例
        textScaleFactor: 1.3,
        style: TextStyle(
            fontSize: 18, // 字体大小
            color: Colors.purple // 文字颜色
        ),
      ),
    );
  }
}
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("TextRich"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      color: Colors.green,
      alignment: Alignment.center,
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(text: "《定风波》\n", style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold, color: Colors.black)),
            TextSpan(text: "苏轼\n", style: TextStyle(fontSize: 18, color: Colors.redAccent)),
            TextSpan(text: "莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。")
          ],
        ),
        style: TextStyle(fontSize: 22, color: Colors.purple),
        textAlign: TextAlign.center,
      ),
    );
  }
}

按钮Widget

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Button"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        FloatingActionButton(
          /// 悬浮的Button
          child: Text("FloatingActionButton"),
          backgroundColor: Colors.green,
          onPressed: () {
            print("FloatingActionButton Click");
          },
        ),
        RaisedButton(
          /// 有突起效果的Button
          child: Text("RaisedButton"),
          textColor: Colors.white,
          color: Colors.green,
          onPressed: () {
            print("RaisedButton Click");
          },
        ),
        FlatButton(
          /// 扁平的Button
          child: Text("FlatButton"),
          textColor: Colors.red,
          color: Colors.yellow,
          onPressed: () {
            print("FlatButton Click");
          },
        ),
        OutlineButton(
          /// 有外边框的Button
          child: Text("OutlineButton"),
          textColor: Colors.orange,
          color: Colors.orange,
          onPressed: () {
            print("OutlineButton Click");
          },
        ),
        /// 自定义button: 图标-文字-背景-圆角
        FlatButton(
          color: Colors.amberAccent,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Icon(
                Icons.favorite,
                color: Colors.red,
              ),
              Text("自定义Button")
            ],
          ),
          onPressed: () {
            print("自定义Button Click");
          },
        ),
        /// 自定义Button
        RaisedButton(
          child: Text("同意协议", style: TextStyle(color: Colors.white)),
          color: Colors.red, // 按钮的颜色
          highlightColor: Colors.orange[700], // 按下去高亮颜色
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), // 圆角的实现
          onPressed: () {
            print("同意协议");
          },
        ),
        /**
         * 1.默认情况下按钮上下有一定的间距,materialTapTargetSize默认是padded
         * 2.如何让默认大小的按钮变小?可以通过ButtonTheme
         * 3.去除按钮的的内边距,可以通过padding属性
         * */
        Column(
          children: <Widget>[
            ButtonTheme(
              minWidth: 1,// 最小宽度,最小为包裹内容的宽度
              height: 1,// 按钮高度,最小为包裹内容的高度
              child: FlatButton(
                padding: EdgeInsets.all(0),// 设置内边距
                color: Colors.red,
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                child: Text("Flat Button1"),
                textColor: Colors.white,
                onPressed: () {},
              ),
            )
          ],
        )
      ],
    );
  }
}

图片Widget

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  final imageURL =
      "https://cdn.pixabay.com/photo/2020/03/24/16/17/mask-4964590_1280.png";

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Image(
          // 加载网络图片
          image: NetworkImage(imageURL),
        ),
        Image(
          // 图片颜色
          color: Colors.purple,
          // 混入模式
          colorBlendMode: BlendMode.colorDodge,
          // 加载网络图片
          image: NetworkImage(imageURL),
          // 图片的宽度
          width: 200,
          // 图片的高度
          height: 200,
          // 图片缩放模式
          fit: BoxFit.contain,
          // 图片占不满控件时是否重复
          repeat: ImageRepeat.repeatY,
          // 范围: -1 ~ 1,(-1,-1)在左上角,(1,1)在右下角
          // Alignment.bottomCenter本质为(0,1)
          alignment: Alignment(1, 1),
        )
      ],
    );
  }
}
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  final imageURL =
      "https://cdn.pixabay.com/photo/2020/03/24/16/17/mask-4964590_1280.png";

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        // 加载本地图片
        Image.asset(
            "assets/images/xuebao.png"
        ),
        // 加载本地图片另一种写法
        Image(
          image: AssetImage("assets/images/xuebao.png"),
        ),
        // 占位图的问题: FadeInImage
        // 图片缓存: 1000张,最大内存缓存100M,再高就有被系统干的风险
        FadeInImage(
          // 淡出时间
          fadeOutDuration: Duration(milliseconds: 1),
          // 淡入时间
          fadeInDuration: Duration(milliseconds: 1),
          // 占位图
          placeholder: AssetImage("assets/images/xuebao.png"),
          // 加载网络图片
          image: NetworkImage(imageURL),
        ),
      ],
    );
    ;
  }
}
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  final imageURL =
      "https://cdn.pixabay.com/photo/2020/03/24/16/17/mask-4964590_1280.png";
  final double headWH = 200;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Center(
          child: CircleAvatar(
            radius: headWH / 2,
            backgroundImage: NetworkImage(imageURL),
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            child: Container(
                alignment: Alignment(0, .5),
                width: headWH,
                height: headWH,
                child: Text("口罩君")),
          ),
        ),
        Center(
          child: ClipOval(
            child: Image.network(
              "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg",
              width: headWH,
              height: headWH,
            ),
          ),
        ),
      ],
    );
  }
}
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  final imageURL =
      "https://cdn.pixabay.com/photo/2020/03/24/16/17/mask-4964590_1280.png";
  final double headWH = 200;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Center(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg",
              width: 200,
              height: 200,
            ),
          ),
        ),
      ],
    );
  }
}
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IconExtensionDemo();
  }
}

class IconExtensionDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /** Icon字体图标
     * 字体图标矢量图(放大的时候不会失真)
     * 字体图标可以设置颜色
     * 图标很多时, 占据空间更小
     * */
    return Icon(Icons.pets, size: 300, color: Colors.green);
    // Icons.pets = IconData(0xe91d, fontFamily: 'MaterialIcons');
//    return Icon(IconData(0xe91d, fontFamily: 'MaterialIcons'), size: 300, color: Colors.orange);

    /** Icon字体图标本质是字符
     * 0xe91d -> unicode编码
     * 设置对应的字体
     * */
//    return Text(
//      "\ue91d",
//      style: TextStyle(
//          fontSize: 100, color: Colors.orange, fontFamily: "MaterialIcons"
//      ),
//    );
  }
}

TextField

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextFieldDemo();
  }
}

class TextFieldDemo extends StatelessWidget {
  final usernameTextEditController = TextEditingController();
  final passwordTextEditController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
          primaryColor: Colors.green
      ),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            TextField(
              /// 绑定控制器,这样就可以获取输入框的值
              controller: usernameTextEditController,
              /// 装饰TextField
              decoration: InputDecoration(
                  // 文本框名称,一般很少这么用
                  labelText: "username",
                  // 设置输入框Icon
                  icon: Icon(Icons.people),
                  // 光标进入时的提示文案
                  hintText: "请输入用户名",
                  // 没有边框
//                  border: InputBorder.none,
                  // 带下划线的边框
                  border: UnderlineInputBorder(),
                  // 设置输入框填充色
                  filled: true,
                  fillColor: Colors.red[100]
              ),
              // 输入框文本发生变化时触发
              onChanged: (value) {
                print("onChange:$value");
              },
              // 点击回车时触发
              onSubmitted: (value) {
                print("onSubmitted:$value");
              },
            ),
            // 设置间距
            SizedBox(height: 15),
            TextField(
              /// 绑定控制器,这样就可以获取输入框的值
              controller: passwordTextEditController,
              decoration: InputDecoration(
                labelText: "password",
                icon: Icon(Icons.lock),
                // 设置外边框
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  borderSide: BorderSide(),
//                  // 设置半天发现没什么卵效果
//                  borderSide: BorderSide(
//                    style: BorderStyle.solid,
//                    color: Colors.red,
//                  ),
                  // 设置labelText gap宽度
                  gapPadding: 10,
                ),
              ),
            ),
            // 设置间距
            SizedBox(height: 10,),
            // 通过此中方式设置按钮的宽高
            Container(
              // 填充整个父容器
              width: double.infinity,
              height: 40,
              child: FlatButton(
                child: Text("登 录", style: TextStyle(fontSize: 20, color: Colors.white),),
                // 设置按钮颜色
                color: Colors.blue,
                onPressed: () {
                  // 1.获取用户名和密码
                  final username = usernameTextEditController.text;
                  final password = passwordTextEditController.text;
                  print("账号:$username 密码:$password");
                  // 清空输入框内容
                  usernameTextEditController.text = "";
                  passwordTextEditController.text = "";
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

Form表单

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Form"),
        ),
        body: HomeView(),
      ),
    );
  }
}

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FormDemo();
  }
}

class FormDemo extends StatelessWidget {
  final usernameTextEditController = TextEditingController();
  final passwordTextEditController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Form(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextFormField(
            /// 绑定控制器,这样就可以获取输入框的值
            controller: usernameTextEditController,
            decoration: InputDecoration(
                // 文本框名称,一般很少这么用
                labelText: "username",
                // 设置输入框Icon
                icon: Icon(Icons.people),
                // 光标进入时的提示文案
                hintText: "请输入用户名",
                // 没有边框
//                  border: InputBorder.none,
                // 带下划线的边框
                border: UnderlineInputBorder(),
                // 设置输入框填充色
                filled: true,
                fillColor: Colors.red[100]
            ),
            // 验证器
            validator: (value) {
              if(value.isEmpty) {
                return "用户名不能为空";
              }

              return null;
            },
            // 自动验证
            autovalidate: true,
          ),
          TextFormField(
            /// 绑定控制器,这样就可以获取输入框的值
            controller: passwordTextEditController,
            obscureText: true,
            decoration: InputDecoration(
              labelText: "password",
              icon: Icon(Icons.lock),
              // 设置外边框
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                borderSide: BorderSide(),
//                  // 设置半天发现没什么卵效果
//                  borderSide: BorderSide(
//                    style: BorderStyle.solid,
//                    color: Colors.red,
//                  ),
                // 设置labelText gap宽度
                gapPadding: 10,
              ),
            ),
            // 验证器
            validator: (value) {
              if(value.isEmpty) {
                return "密码不能为空";
              }

              return null;
            },
            // 自动验证
            autovalidate: true,
          ),
          SizedBox(
            height: 16,
          ),
          Container(
            width: double.infinity,
            height: 44,
            child: RaisedButton(
              color: Colors.lightGreen,
              child: Text(
                "注 册",
                style: TextStyle(fontSize: 20, color: Colors.white),
              ),
              onPressed: () {
                print("点击了注册按钮");

                // 1.获取用户名和密码
                final username = usernameTextEditController.text;
                final password = passwordTextEditController.text;

                print("账号:$username 密码:$password");
              },
            ),
          )
        ],
      ),
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读