侧边栏壁纸
  • 累计撰写 32 篇文章
  • 累计创建 13 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Flutter-Widget介绍

javalx
2022-06-22 / 0 评论 / 0 点赞 / 18 阅读 / 24817 字

前言

Flutter中几乎所有的对象都是一个Widget(组件),包括两大类,分别是StatelessWidget(无状态Widget)和StatefulWidget(有状态Widget)。在编写应用程序时,通常会创建新的widget,这些widget是无状态的StatelessWidget或者是有状态的StatefulWidget, 具体的选择取决于您的widget是否需要管理一些状态(控件的文字、颜色、数据等进行刷新更改)。

StatelessWidget

常用组件库

graph LR
O(StatelessWidget)------> A(Container 容器)
O(StatelessWidget)------> B(Text 文本)
O(StatelessWidget)------> C(Icon 图标)
O(StatelessWidget)------> D(CloseButton 关闭按钮)
O(StatelessWidget)------> E(BackButton 返回按钮)
O(StatelessWidget)------> F(Chip 标签)
O(StatelessWidget)------> G(Divider 分隔线)
O(StatelessWidget)------> H(Card 卡片快)
O(StatelessWidget)------> I(AlertDialog 弹框)

实践示例

Container

  • 代码

    /*
     * @Descripttion: 无状态组件使用
     * @version: 
     * @Author: javalx
     * @Date: 2022-09-04 16:08:05
     * @LastEditors: javalx
     * @LastEditTime: 2022-09-07 11:18:00
     */
    import 'dart:ui';
    import 'package:flutter/material.dart';
    
    class StatelessPage extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        // 样式定义
        TextStyle textStyle = TextStyle(color: Colors.red, fontSize: 20);
          
        return MaterialApp(
          title: "StatelessWidget无状态组件",
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              centerTitle: true,
              title: Text("StatelessWidget示例"),
            ),
            body: Container(
              decoration: BoxDecoration(color: Colors.white10),
              alignment: Alignment.center,
              child: Column(
                children: <Widget>[
                  // 主要代码
                  Text("I am Text", style: textStyle),
                ],
              ),
            ),
          ),
        );
      }
    }
    
  • 图例

    image-20220907114841801

  • 说明

    Container是Flutter里很常用的一个组件,类似于html中的div

    参数名称参数类型参数说明参数示例
    alignmentAlignmentGeometry设置子元素的对齐方式Alignment(1.0, 0.0)
    paddingEdgeInsetsGeometry内边距,设置子元素的填充方式EdgeInsets.fromLTRB(10, 5, 0, 1)
    colorColor设置简单的背景颜色Colors.red、Colors.green
    decorationDecoration背景装饰器:设置背景色、背景图、边框、圆角、阴影、渐变色等BoxDecoration(color: Colors.white)
    foregroundDecorationDecoration前景装饰器:同上BoxDecoration(color: Colors.white)
    widthdouble设置Container的宽度400
    heightdouble设置Container的高度600
    constraintsBoxConstraintsContainer的大小可以通过widthheight来指定,也可以通过constraints来指定;当它们同时存在时,widthheight优先;实际上Container内部会根据widthheight来生成一个constraintsBoxConstraints.expand()
    marginEdgeInsetsGeometry外边距EdgeInsets.all(5)
    transformMatrix4变换:控制子组件的平移、旋转、缩放、倾斜Matrix4.rotationZ(0.5)
    transformAlignmentAlignmentGeometry设置变换的锚点Alignment(0, 0)
    childWidget子元素Text("I am Text")
    clipBehaviorClip剪切Clip.none

Text

  • 代码

    // 样式定义
    TextStyle textStyle = TextStyle(color: Colors.red, fontSize: 20);
    // 主要代码
    Text("I am Text", style: textStyle),
    
  • 图例

    image-20220907112204547

    image-20220907113921725

  • 说明

    参数名称参数类型参数说明参数示例
    dataString文本内容"I am Text"
    styleTextStyle文本样式TextStyle(color: Colors.red)
    strutStyleStrutStyle文本布局样式,字体偏移等,使用时 style 属性必须有值StrutStyle(leading: 2)
    textAlignTextAlign文本对齐方式TextAlign.left
    textDirectionTextDirection文本方向,和 textAlign 效果一致TextDirection.ltr
    localeLocale区域设置,基本不会用
    softWrapbool是否自动换行true
    overflowTextOverflow超出截取方式,clip->直接截取,fade->渐隐,ellipsis->省略号TextOverflow.ellipsis
    textScaleFactordouble字体缩放1.25
    maxLinesint最多显示行数3
    semanticsLabelString语义标签,如文本为"$$",这里设置为"双美元"
    textWidthBasisTextWidthBasis测量行宽度TextWidthBasis.longestLine
    textHeightBehaviorui.TextHeightBehavior官方备注: 定义如何应用第一行的ascent和最后一行的descent

Icon

  • 代码

    Icon(
        Icons.android,
        size: 50,
    )
    
  • 图例

    image-20220907113715349

  • 说明

    参数名称参数类型参数说明参数示例
    iconIconData图标Icons.android
    sizedouble大小50
    colorColor颜色Colors.amber
    semanticLabelString语义标签"村上春树"
    textDirectionTextDirection文本方向TextDirection.ltr

CloseButton

  • 代码

    CloseButton(
    	color: Colors.greenAccent,
    )
    
  • 图例

    image-20220907115417214

  • 说明

    参数名称参数类型参数说明参数示例
    colorColors按钮颜色Colors.greenAccent
    onPressedFunction点击事件(){...}

BackButton

  • 代码

    BackButton(
    	color: Colors.amberAccent,
    )
    
  • 图例

    image-20220907141843895

  • 说明

    参数名称参数类型参数说明参数示例
    colorColors按钮颜色Colors.greenAccent
    onPressedFunction点击事件(){...}

Chip

  • 代码

    Chip(
    	avatar: Icon(
    		Icons.people,
    		color: Colors.deepOrangeAccent,
    	),
        label: Text(
        	"尼古拉斯-赵四",
        style: TextStyle(color: Colors.pink),
    ))
    
  • 图例

    image-20220907143003440

  • 说明

    参数名称参数类型参数说明参数示例
    avatarIcon左侧图标组件Icon(Icons.people)
    labelWidget@required 文本Text("尼古拉斯-赵四")
    labelStyleTextStyle文本样式TextStyle(color: Colors.green)
    labelPaddingEdgeInsetsGeometry文本外边距EdgeInsets.fromLTRB(10, 20, 0, 5)
    deleteIconWidget右侧删除按钮Icon(Icons.close)
    onDeletedFunction删除按钮点击事件() {...}
    deleteIconColorColor删除按钮颜色Colors.green
    useDeleteButtonTooltipbool开启删除按钮提示true
    deleteButtonTooltipMessageString删除按钮的长安提示"长按提示!"
    sideBorderSide设置外边线new BorderSide(style: BorderStyle.solid, color: Colors.green))
    shapeOutlinedBorder设置包裹形状RoundedRectangleBorder(borderRadius: BorderRadius.circular(2.0))
    clipBehaviorClip裁剪方式Clip.none
    focusNodeFocusNode焦点控制
    autofocusbool自动聚焦,默认为 falsetrue
    backgroundColorColor背景色Colors.white70
    paddingEdgeInsetsGeometry内边距EdgeInsets.fromLTRB(0, 10, 0, 0)
    visualDensityVisualDensity紧凑程度VisualDensity.compact
    materialTapTargetSizeMaterialTapTargetSize内边距,设置感应区域MaterialTapTargetSize.padded、MaterialTapTargetSize.shrinkWrap
    elevationdouble阴影高度,默认为 010
    shadowColorColor阴影颜色Colors.blue

Divider

  • 代码

    Divider(
        color: Colors.green,
        height: 10.0,
        indent: 5,
        endIndent: 5,
        thickness: 2,
    )
    
  • 图例

    image-20220907143505687

  • 说明

    参数名称参数类型参数说明参数示例
    colorColors按钮颜色Colors.greenAccent
    heightdouble组件整体高度10
    indentdouble分割线前距离(左间距)5
    endIndentdouble分割线后距离(右间距)5
    thicknessdouble线的高度2

Card

  • 代码

    Card(
        color: Colors.grey,
        shadowColor: Colors.redAccent,
        elevation: 4,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
            side: BorderSide(
                color: Colors.greenAccent,
                width: 3,
            ),
        ),
        margin: EdgeInsets.all(8),
        child: Container(
            padding: EdgeInsets.all(8),
            child: Text(
                "我大抵是病了,横竖都睡不着,坐起身来点起了一支烟,这悲伤没有由来,黯然看着床头的两个枕头,一个是我的,另一个也是我的……",
                style: TextStyle(
                    fontFamily: "微软雅黑",
                    fontSize: 22,
                    color: Colors.black,
                ),
            )),
    )
    
  • 图例

    image-20220907150715710

  • 说明

    参数名称参数类型参数说明参数示例
    colorColor背景颜色Colors.grey
    elevationdouble阴影高度10
    shadowColordouble阴影颜色Colors.blue
    shapeShapeBorder卡片形状RoundedRectangleBorder(borderRadius: BorderRadius.circular(10), side: BorderSide(color: Colors.greenAccent, width: 3))
    borderOnForegroundbool是否在 child 前绘制 border,默认为 truetrue
    marginEdgeInsetsGeometry外边距EdgeInsets.all(8)
    clipBehaviorClip裁剪方式Clip.none
    childWidget子组件Container()
    semanticContainerbool是否使用新的语义节点,默认为 true。语义这个东西用途没有那么大,在看页面层级的Debug 模式下组件展示方式会按照设置的语义标签展示。true

AlertDialog

  • 代码

    AlertDialog(
        title: Text("弹框标题!"),
        titleTextStyle: TextStyle(color: Colors.orange),
        content: Text("AlertDialog 是一个弹框组件,这是他的内容!"),
    )
    
  • 图例

    image-20220907151536428

  • 说明

    参数名称参数类型参数说明参数示例
    titleWidget标题"标题XXX"
    titlePaddingEdgeInsetsGeometry标题外间距EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0)
    titleTextStyleTextStyle标题样式TextStyle(color: Colors.orange)
    contentWidget内容组件Text("弹框组件的内容!")
    contentPaddingEdgeInsetsGeometry内容外间距EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0)
    contentTextStyleTextStyle内容文本样式TextStyle(color: Colors.orange)
    actionsList事件子组件[FlatButton(onPressed: (){...}, child: Text("cancel")), FlatButton(onPressed: (){...}, child: Text("ok"))]
    actionsPaddingEdgeInsetsGeometry事件子控件间距EdgeInsets.zero
    actionsOverflowDirectionVerticalDirection事件过多竖向展示时顺序VerticalDirection.down
    actionsOverflowButtonSpacingdouble事件竖向展示时组件间距10
    buttonPaddingEdgeInsetsGeometryactions 中每个按钮边缘填充距离EdgeInsets.all(8)
    backgroundColorColor背景色Colors.orange
    elevationdouble阴影高度10
    semanticLabelString语义标签
    insetPaddingEdgeInsets对话框距离屏幕边缘间距EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0)
    clipBehaviorClip超出部分剪切方式Clip.none
    shapeShapeBorder形状RoundedRectangleBorder(borderRadius: BorderRadius.circular(10), side: BorderSide(color: Colors.greenAccent, width: 3))
    scrollablebool是否可以滚动false

StatefulWidget

常用组件库

graph LR
StatefulWidget--> A(MaterialApp 材料设计)
StatefulWidget--> B(Scaffold 脚手架)
StatefulWidget--> C(AppBar 顶部应用栏)
StatefulWidget--> D(ButtonNavigationBar 底部导航栏)
StatefulWidget--> E(RefreshIndicator 下拉刷新)
StatefulWidget--> F(Image 图片)
StatefulWidget--> G(TextField 输入框)
StatefulWidget--> H(PageView 页面浏览)

实践示例

MaterialApp

  • 代码

    MaterialApp(
        title: "StatelessWidget无状态组件",
        theme: ThemeData(
            primarySwatch: Colors.blue,
        ),
        ......
        ...
    )
    
  • 图例

    image-20220908170438661

  • 说明

    参数名称参数类型参数说明参数示例
    navigatorKeyGlobalKey导航键
    scaffoldMessengerKeyGlobalKey脚手架键
    homeWidget主页,应用打开时显示的页面Scaffold()
    routesMap<String, WidgetBuilder>应用程序顶级路由表
    initialRouteString如果构建了导航器,则会显示第一个路由的名称
    onGenerateRouteRouteFactory路由管理拦截器
    onGenerateInitialRoutesInitialRouteListFactory生成初始化路由
    onUnknownRouteRouteFactory当onGenerateRoute无法生成路由时调用
    navigatorObserversList创建导航器的观察者列表
    builderTransitionBuilder在导航器上面插入小部件
    titleString程序切换时显示的标题
    onGenerateTitleGenerateAppTitle程序切换时生成标题字符串
    colorColor程序切换时应用图标背景颜色(仅安卓有效)
    themeThemeData主题颜色ThemeData(primarySwatch: Colors.blue)
    darkThemeThemeData暗黑模式主题颜色
    highContrastThemeThemeData系统请求“高对比度”使用的主题
    highContrastDarkThemeThemeData系统请求“高对比度”暗黑模式下使用的主题颜色
    themeModeThemeMode使用哪种模式的主题(默认跟随系统)
    localeLocale初始区域设置
    localizationsDelegatesIterable<LocalizationsDelegate>本地化代理
    localeListResolutionCallbackLocaleListResolutionCallback失败或未提供设备的语言环境
    localeResolutionCallbackLocaleResolutionCallback负责计算语言环境
    supportedLocalesIterable本地化地区列表
    debugShowMaterialGridbool绘制基线网格叠加层(仅debug模式)
    showPerformanceOverlaybool显示性能叠加
    checkerboardRasterCacheImagesbool打开栅格缓存图像的棋盘格
    checkerboardOffscreenLayersbool打开渲染到屏幕外位图的层的棋盘格
    showSemanticsDebuggerbool打开显示可访问性信息的叠加层
    debugShowCheckedModeBannerbool调试显示检查模式横幅
    shortcutsMap<LogicalKeySet, Intent>应用程序意图的键盘快捷键的默认映射
    actionsMap<Type, Action>包含和定义用户操作的映射
    restorationScopeIdString应用程序状态恢复的标识符

Scaffold

  • 代码

    Scaffold(
        appBar: ...,
        body: ...,
        ......
        ...
    )
    
  • 图例

    image-20220908170802756

  • 说明

AppBar 顶部应用栏

  • 代码

    AppBar(
        centerTitle: true,
        title: Text("StatefulWidget示例"),
    )
    
  • 图例

    image-20220908171254730

  • 说明

ButtonNavigationBar 底部导航栏

  • 代码

    class StatefulPageState extends State<StatefulPage> {
      int currentIndex = 0;
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: "StatefulWidget有状态组件",
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(
              centerTitle: true,
              title: Text("顶部标题"),
            ),
            bottomNavigationBar: BottomNavigationBar(
              currentIndex: currentIndex,
              items: [
                BottomNavigationBarItem(
                    icon: Icon(
                      Icons.home,
                      color: Colors.grey,
                    ),
                    activeIcon: Icon(
                      Icons.home,
                      color: Colors.blue,
                    ),
                    label: "首页"),
                BottomNavigationBarItem(
                    icon: Icon(
                      Icons.list,
                      color: Colors.grey,
                    ),
                    activeIcon: Icon(
                      Icons.list,
                      color: Colors.blue,
                    ),
                    label: "列表")
              ],
              onTap: (value) {
                setState(() {
                  currentIndex = value;
                });
              },
            ),
          )
        )
      }
    }
    
  • 图例

    image-20220908172149704

    image-20220908173019456image-20220908173057401

  • 说明

RefreshIndicator 下拉刷新

  • 代码

    AlertDialog(
        title: Text("弹框标题!"),
        titleTextStyle: TextStyle(color: Colors.orange),
        content: Text("AlertDialog 是一个弹框组件,这是他的内容!"),
    )
    
  • 图例

    image-20220908173812477

  • 说明

Image 图片

  • 代码

    Image.network(
    	"https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/mark:3024:3024:3024:1702.awebp",
    ),
    
  • 图例

    image-20220909095152738

  • 说明

TextField 输入框

  • 代码

    TextField(
        decoration: InputDecoration(
            contentPadding: EdgeInsets.fromLTRB(5, 0, 0, 0),
            hintText: "请输入用户名",
            hintStyle: TextStyle(fontSize: 18, color: Colors.grey)
        ),
        style: TextStyle(fontSize: 22, color: Colors.blue),
    ),
    
  • 图例

    image-20220909100112319

  • 说明

PageView 页面浏览

  • 代码

    Container(
        height: 200,
        margin: EdgeInsets.all(5),
        decoration: BoxDecoration(color: Colors.lightGreen),
        child: PageView(
            children: [
                _item("Page 1", Colors.redAccent),
                _item("Page 2", Colors.greenAccent),
                _item("Page 3", Colors.blueAccent),
                _item("Page 4", Colors.orangeAccent)
            ],
        ),
    )
        
    _item(String title, Color color) {
        return Container(
            decoration: BoxDecoration(color: color),
            child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.black),
            ),
        );
    }
    
  • 图例

    image-20220909100356104

  • 说明

0

评论区