美文网首页
Flutter 组件之 Widget、Container、Tex

Flutter 组件之 Widget、Container、Tex

作者: Abner_XuanYuan | 来源:发表于2023-10-08 16:02 被阅读0次

    1、Widget

    Widget 是 Flutter 的组件、控件,在 Flutter 中万物皆 Widget。(iOS/Android 中的Application、ViewController、Activity、View、Button等等,在 Flutter 中,用不同的 Widget 表示)
    在 Flutter 开发中,通过继承 StatelessWidgetStatefulWidget 来创建 Widget 类。
    StatelessWidget: 没有状态改变的 Widget,数据通常是直接写死。(通常这种 Widget 仅仅是做一些展示工作而已)
    StatefulWidget: 需要保存状态并且可能出现状态改变的 Widget。

    1、StatelessWidget
    class name extends StatelessWidget {
      const name({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Container();//<要渲染的 Widget,比如:Text Widget>
      }
    }
    
    2、StatefulWidget
    class name extends StatefulWidget {
      const name({super.key});
    
      @override
      State<name> createState() => _nameState();
    }
    
    class _nameState extends State<name> {
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    

    Flutter 将 StatefulWidget 设计成了两个类:
    1、一个类继承自 StatefulWidget,作为 Widget 树的一部分。
    2、一个类继承自 State,用于记录 StatefulWidget 会变化的状态,并且根据状态的变化,构建出新的 Widget。

    build 方法作用:渲染 Widget。

    build 方法什么情况下被执行
    1、当我们的 StatelessWidget 第一次被插入到 Widget 树中时(也就是第一次被创建时)。
    2、当我们的父 Widget(parent widget)发生改变时,子 Widget 会被重新构建。
    3、如果我们的 Widget 依赖 InheritedWidget 的一些数据,InheritedWidget 数据发生改变时。

    3、Widget 生命周期

    StatelessWidget 可以由父 Widget 直接传入值,调用 build 方法来构建,整个过程非常简单。
    StatefulWidget 需要通过 State 来管理其数据并且还要监控状态的改变决定是否重新 build 整个 Widget。

    StatelessWidget 生命周期
    1、执行 StatelessWidget 的构造函数(Constructor)来创建出 StatelessWidget。
    2、执行 build 方法。

    StatefulWidget 生命周期
    StatefulWidget 由两个类组成:StatefulWidgetState
    StatefulWidget
    1、执行 StatefulWidget 的构造函数(Constructor)来创建出 StatefulWidget。
    2、执行 StatefulWidget 的 createState 方法,来创建一个维护 StatefulWidget 的 State 对象。

    State:
    调用 createState 创建 State 对象时,执行 State 类的相关方法:
    1、执行 State 类的构造方法(Constructor)来创建 State 对象。
    2、执行 initState(我们通常会在这个方法中执行一些数据初始化的操作或者也可能会发送网络请求)。
    3、执行 didChangeDependencies 方法,该方法会在调用 initState依赖数据发生改变时情况下调用。
    4、执行 build 方法,渲染 Widget。
    5、当前的 Widget 不再使用时,会调用 dispose 进行销毁。

    注:
    1、手动调用 setState 方法,会根据最新的状态(数据)来重新调用 build 方法,构建对应的 Widgets。
    2、执行 didUpdateWidget 方法是在当父 Widget 触发重建(rebuild)时,系统会调用 didUpdateWidget 方法。

    2、Container

    Container 组件类似于 iOS 中的 UIView,主要负责视图的承载,可以通过它设置背景色、边框、圆角等等。

      Container({
        Key? key,
        this.alignment, //AlignmentGeometry 类型可选命名参数,容器内子 Widget 如何对其,使用其子类 Alignment
        this.padding, //EdgeInsetsGeometry类型可选命名参数,设置容器内边距
        this.color, //Color类型可选命名参数,容器填充色
        this.decoration, //Decoration类型可选命名参数,绘制在child子Widget后面的装饰,使用BoxDecoration
        this.foregroundDecoration, //Decoration类型可选命名参数,绘制在child子Widget前面的装饰,使用BoxDecoration
        double? width, //double类型可选命名参数,容器的宽度
        double? height, //double类型可选命名参数,容器的高度
        BoxConstraints? constraints, //BoxConstraints类型可选命名参数,对child设置的Widget的约束
        this.margin, //EdgeInsetsGeometry类型可选命名参数,设置容器外边距
        this.transform, //Matrix4类型可选命名参数,在绘制容器之前要应用的转换矩阵
        this.transformAlignment, //变换时,对于容器大小的对齐
        this.child, //Widget类型可选命名参数,容器包含的子Widget
        this.clipBehavior = Clip.none, //剪辑原则,默认是Clip.none
      })
    

    alignment
    topCenter:顶部居中对齐
    topLeft:顶部左对齐
    topRight:顶部右对齐
    center:水平垂直居中对齐
    centerLeft:垂直居中水平居左对齐
    centerRight:垂直居中水平居右对齐
    bottomCenter:底部居中对齐
    bottomLeft:底部居左对齐
    bottomRight:底部居右对齐

    示例

    import 'package:flutter/material.dart';
    
    void main(List<String> args) {
      runApp(MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("第二个 Flutter"),
            foregroundColor: Colors.green,
          ),
          backgroundColor: Colors.orange,
          body: const MyApp(),
        ),
      ));
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Container(
            alignment: Alignment.center,
            height: 200,
            width: 200,
            decoration: BoxDecoration(
                color: Colors.yellow,
                gradient: const LinearGradient(
                  //LinearGradient 背景线性渐变 RadialGradient径向渐变
                  colors: [Colors.red, Colors.orange],
                ),
                boxShadow: const [
                  //卡片阴影
                  BoxShadow(
                    color: Colors.blue,
                    offset: Offset(2.0, 2.0),
                    blurRadius: 10.0,
                  )
                ],
                border: Border.all(color: Colors.black, width: 1)),
            transform: Matrix4.rotationZ(.2),
            child: const Text(
              "你好Flutter",
              style: TextStyle(fontSize: 20),
            ),
          ),
        );
      }
    }
    
    //按钮
    
    import 'package:flutter/material.dart';
    
    void main(List<String> args) {
      runApp(MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("第二个 Flutter"),
            foregroundColor: Colors.green,
          ),
          backgroundColor: Colors.orange,
          body: const MyApp(),
        ),
      ));
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Container(
            alignment: Alignment.center,
            height: 40,
            width: 200,
            decoration: BoxDecoration(
                color: Colors.blue, borderRadius: BorderRadius.circular(15)),
            child: const Text(
              "按钮",
              style: TextStyle(fontSize: 20),
            ),
          ),
        );
      }
    }
    

    BoxDecoration

    const BoxDecoration({
      //Color类型可选命名参数,填充背景色
      this.color,
      //DecorationImage类型可选命名参数,在背景或渐变上绘制的图像
      this.image,
      //BoxBorder类型可选命名参数,边框设置
      this.border,
      //BorderRadiusGeometry类型可选命名参数,设置圆角
      this.borderRadius,
      //List<BoxShadow>类型可选命名参数,盒子后面的盒子投射的阴影列表
      this.boxShadow,
      //Gradient类型可选命名参数,填充框时使用的渐变
      this.gradient,
      //BlendMode类型可选命名参数,应用于框的颜色或渐变背景的混合模式
      this.backgroundBlendMode,
      //BoxShape类型可选命名参数,将背景颜色、渐变和图像填充到并作为boxShadow投射的形状
      this.shape = BoxShape.rectangle,
    })
    

    示例

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Container(
          // width: 400,
          // height: 400,
          padding: const EdgeInsets.all(20),
    
          color: Colors.lightBlue,
          child: Container(
              width: 280,
              height: 280,
              //内边距
              // padding: EdgeInsets.all(100),
              //外边距
              // margin: EdgeInsets.all(80),
              // 不可与 decoration 同时设置
              // color: Colors.red,
              //变形:旋转
              transform: Matrix4.rotationZ(0.1),
              //装饰:设置颜色。渐变色、形状、阴影等。
              decoration: BoxDecoration(
                  color: Colors.green,
                  //渐变
                  gradient: const LinearGradient(
                      colors: [Colors.blue, Colors.red, Colors.green]),
                  //形状
                  shape: BoxShape.circle,
                  //阴影
                  boxShadow: const [
                    BoxShadow(offset: Offset(10, 10), color: Colors.grey)
                  ],
                  backgroundBlendMode: BlendMode.srcOver,
                  border: Border.all(color: Colors.orange, width: 5)),
              child: const Icon(
                Icons.people,
                color: Colors.orange,
                size: 100,
              )),
        );
      }
    }
    

    3、Text

    Text 继承自 StatelessWidget,Text 主要通过设置文本布局文本样式控制显示方式。
    文本布局:例如:文本对齐方式 textAlign、文本排版方向 textDirection,文本显示最大行数 maxLines、文本截断规则 overflow 等等。
    文本样式:例如:字体名称 fontFamily、字体大小 fontSize、文本颜色 color、文本阴影 shadows 等等,这些参数被统一封装到了构造函数中的参数 style(TextStyle) 中。

    1、Text
    const Text(
      //String类型必传参数,为要显示的文本字符串
      this.data, {
      //以下为可选命名参数
      //  
      Key key,
      //TextStyle类型可选参数,用于设置文本的样式  
      this.style,
      //StrutStyle类型可选参数,用于设置文本支撑样式  
      this.strutStyle,
      //TextAlign类型可选参数,用于设置文本水平方向如何对齐
      this.textAlign,
      //TextDirection类型参数,用于设置文本的显示方向(从左到右或从右到左)  
      this.textDirection,
      //Locale类型参数,用于设置多语言,可以根据不同的区域设置以不同的方式呈现相同的 Unicode 字符。
      this.locale,
      //bool类型参数,用于设置文本是否自动换行,如果为 `true` ,自动换行显示,`false` 则不换行
      //在一行显示,超出屏幕部分不显示。默认为 `true`   
      this.softWrap,
      //TextOverflow类型参数,用于设置文本溢出时如何显示
      this.overflow,
      //double类型参数,用于设置文本的缩放倍数  
      this.textScaleFactor,
      //int类型参数,用于设置最大显示行数,如果超出限制则会根据 overflow 设置的溢出样式显示   
      this.maxLines,
      //String类型参数,于设置显示文本的替代语义标签 
      this.semanticsLabel,
      //TextWidthBasis类型参数 ,用于设置如何测量渲染文本的宽度  
      this.textWidthBasis,
    })
    
    2、TextStyle
     const TextStyle({
      //是否将空值替换为父级Widget文本样式中的值,也就是子Widget在没有定义样式
      //的情况下是否继承父级Widget中的文本样式
      this.inherit = true,
      //Color类型对象,用于设置文本字体颜色
      this.color,
      //Color类型对象,用于设置文本背景色
      this.backgroundColor,
      //double类型可选参数,字体大小
      this.fontSize,
      //FontWeight类型参数,粗体
      this.fontWeight,
      //FontStyle类型参数,设置字体样式,如斜体等
      this.fontStyle,
      //double类型可选参数,设置字母间距(空格)
      this.letterSpacing,
      //double类型可选参数,设置单词之间的间距
      this.wordSpacing,
      //TextBaseline类型可选参数,用于设置不同范围文本间的对齐基线
      this.textBaseline,
      //double类型可选参数,设置文本跨度的高度。当height为null或省略时,
      //行高将直接由字体的度量标准确定,这可能与fontSize不同。当height
      //为非空时,文本范围的行高将是fontSize的倍数,并且正好是fontSize * height逻辑像素高
      this.height,
      //Locale类型可选参数,多语言
      this.locale,
      //Paint类型可选参数,绘制文本的前景样式,比如描边文字等
      this.foreground,
      //Paint类型可选参数,绘制文本的背景样式,可以设置填充,描边,画笔宽度等
      this.background,
      //List<ui.Shadow>类型可选参数,用于在文字下方绘制阴影
      this.shadows,
      //List<FontFeature>类型可选参数,用于设置影响显示字体样式的列表
      this.fontFeatures,
      //TextDecoration类型可选参数,用于设置文字附近的装饰,例如下划线
      this.decoration,
      //Color类型可选参数,用于设置文字装饰的颜色
      this.decorationColor,
      //TextDecorationStyle类型参数,用于设置文字装饰的样式
      this.decorationStyle,
      //double类型可选参数,设置文字装饰的笔触的粗细诚意字体定义的粗细
      this.decorationThickness,
      //String类型可选参数,文本风格调式,调试版本可用
      this.debugLabel,
      //String类型可选参数,用于设置绘制文本时使用的字体名称
      String fontFamily,
      //list<String>类型可选参数,当在较高优先级的字体系列中找不到字形时,字体系列的有序列表将重新出现
      List<String> fontFamilyFallback,
      //String类型可选参数,要使用包中定义的字体系列,必须提供package参数
      String package,
    })
    
    3、富文本

    Text.rich()

    //富文本设置 Text.rich()
    class Text_RichDemo extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Text.rich(TextSpan(children: [
          TextSpan(
              text: "《定风波》",
              style: TextStyle(
                  fontSize: 25, fontWeight: FontWeight.bold, color: Colors.black)),
          TextSpan(
              text: "苏轼", style: TextStyle(fontSize: 18, color: Colors.redAccent)),
          TextSpan(
              text: "\n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。",
              style: TextStyle(color: Colors.blue, fontSize: 20))
        ]));
      }
    }
    

    RichText()

    //富文本设置 RichText()
    class RishTextDemo2 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return RichText(
          text: TextSpan(children: [
            TextSpan(
                text: "《定风波》",
                style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                    color: Colors.black)),
            TextSpan(
                text: "苏轼",
                style: TextStyle(fontSize: 18, color: Colors.redAccent)),
            TextSpan(
                text: "\n莫听穿林打叶声,何妨吟啸且徐行。\n竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。",
                style: TextStyle(color: Colors.blue, fontSize: 20))
          ]),
        );
      }
    }
    

    相关文章

      网友评论

          本文标题:Flutter 组件之 Widget、Container、Tex

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