当前位置:   article > 正文

Flutter基础 -- Flutter常用组件_flutter 组件库

flutter 组件库

目录

1. 文本组件 Text

1.1 基础用法

1.2 Text 定义

1.3 Text 示例

1.4 Text.rich、RichText 、TextSpan

1.5 RichText 示例

2. 导入资源

2.1 加入资源

2.2 加入图片

3. 图片组件 image

3.1 colorBlendMode 混合参数

3.2 fit 图片大小适配

3.3 ImageProvider 图片对象

4. 图标组件 Icon

4.1 定义

4.2 开启 pubspec.yaml

4.3 icon 预览

4.4 示例

4.5 苹果 Icon

5. 按钮组件

5.1 ElevatedButton

5.2 ButtonStyle 样式定义

5.3 其它按钮

6. 路由管理v1 Navigator 

6.1 匿名路由 

6.1.1 Navigator 路由管理对象

6.1.2 MaterialPageRoute 定义

6.1.3 路由传值

6.1.4 示例

6.2 命名路由

6.3 onGenerateRoute 手动解析

6.3.1 定义路由

6.3.2 导航页完整代码

7. 样式管理

7.1 ThemeData 样式对象

7.2 Color 与 MaterialColor

8. 手势事件

8.1 GestureDetector

8.2 InkWell

9. 输入框 TextField

9.1 定义

9.2 示例


博主wx:yuanlai45_csdn 博主qq:2777137742

后期会创建粉丝群,为同学们提供分享交流平台以及提供官方发送的福利奖品~

1. 文本组件 Text

Text Widget,从名字也可以看出,在 Flutter 里是用来负责显示文本信息的一个组件,功能类似于 Android 的 TextView、HTML 的一些文本标签等等,属于基础组件

Text class - widgets library - Dart API

1.1 基础用法

Text('hello word!');

1.2 Text 定义

  1. const Text(
  2. //要显示的文字内容
  3. this.data,
  4. {
  5. //key类似于id
  6. Key key,
  7. //文字显示样式和属性
  8. this.style,
  9. this.strutStyle,
  10. //文字对齐方式
  11. this.textAlign,
  12. //文字显示方向
  13. this.textDirection,
  14. //设置语言环境
  15. this.locale,
  16. //是否自动换行
  17. this.softWrap,
  18. //文字溢出后处理方式
  19. this.overflow,
  20. //字体缩放
  21. this.textScaleFactor,
  22. //最大显示行数
  23. this.maxLines,
  24. //图像的语义描述,用于向Andoid上的TalkBack和iOS上的VoiceOver提供图像描述
  25. this.semanticsLabel,
  26. })

TextStyle 定义

style 属性比较常用,传入的是 TextStyle 对象,我们细看下它可以配置哪些属性样式

  1. const TextStyle({
  2. //是否继承父类组件属性
  3. this.inherit = true,
  4. //字体颜色
  5. this.color,
  6. //文字大小,默认14px
  7. this.fontSize,
  8. //字体粗细
  9. this.fontWeight,
  10. //字体样式,normal或italic
  11. this.fontStyle,
  12. //字母间距,默认为0,负数间距缩小,正数间距增大
  13. this.letterSpacing,
  14. //单词间距,默认为0,负数间距缩小,正数间距增大
  15. this.wordSpacing,
  16. //字体基线
  17. this.textBaseline,
  18. //行高
  19. this.height,
  20. //设置区域
  21. this.locale,
  22. //前景色
  23. this.foreground,
  24. //背景色
  25. this.background,
  26. //阴影
  27. this.shadows,
  28. //文字划线,下换线等等装饰
  29. this.decoration,
  30. //划线颜色
  31. this.decorationColor,
  32. //划线样式,虚线、实线等样式
  33. this.decorationStyle,
  34. //描述信息
  35. this.debugLabel,
  36. //字体
  37. String fontFamily,
  38. List<String> fontFamilyFallback,
  39. String package,
  40. })

1.3 Text 示例

TextStyle class - painting library - Dart API

颜色、大小、样式

  1. Text('字体24下划线',
  2. style: TextStyle(
  3. color: Colors.blue, // 蓝色
  4. fontSize: 24, // 24 号字体
  5. decoration: TextDecoration.underline, // 下划线
  6. )),

缩放、加粗

  1. Text('放大加粗',
  2. textScaleFactor: 1.2, // 放大 1.2
  3. style: TextStyle(
  4. fontWeight: FontWeight.bold, // 加粗 bold
  5. fontSize: 24, // 24 号字体
  6. color: Colors.green, // 绿色
  7. decoration: TextDecoration.none, // 不要下滑线
  8. )),

文字溢出

  1. Text(
  2. '缩放,Each line here is progressively more opaque. The base color is material.Colors.black, and Color.withOpacity is used to create a derivative color with the desired opacity. The root TextSpan for this RichText widget is explicitly given the ambient DefaultTextStyle, since RichText does not do that automatically. The inner TextStyle objects are implicitly mixed with the parent TextSpans TextSpan.style.',
  3. textScaleFactor: 1.0,
  4. textAlign: TextAlign.center,
  5. softWrap: true,
  6. maxLines: 3, // 3 行
  7. overflow: TextOverflow.ellipsis, // 剪切 加省略号
  8. style: TextStyle(
  9. fontWeight: FontWeight.bold,
  10. fontSize: 18,
  11. )),

输出

1.4 Text.rich、RichText 、TextSpan

可以在 Text 里加入一些 Span 标签,对某部分文字进行个性化改变样式,如加入 @ 符号,加入超链接、变色、加表情等等。Text.rich(…) 等价于 RichText(...),用哪个都可以。

https://api.flutter.dev/flutter/widgets/RichText-class.html

 定义

  1. const Text.rich(
  2. // 样式片段标签TextSpan
  3. this.textSpan,
  4. {
  5. Key key,
  6. this.style,
  7. this.strutStyle,
  8. this.textAlign,
  9. this.textDirection,
  10. this.locale,
  11. this.softWrap,
  12. this.overflow,
  13. this.textScaleFactor,
  14. this.maxLines,
  15. this.semanticsLabel,
  16. })
  17. const RichText({
  18. Key key,
  19. // 样式片段标签TextSpan
  20. @required this.text,
  21. this.textAlign = TextAlign.start,
  22. this.textDirection,
  23. this.softWrap = true,
  24. this.overflow = TextOverflow.clip,
  25. this.textScaleFactor = 1.0,
  26. this.maxLines,
  27. this.locale,
  28. this.strutStyle,
  29. })

textSpan 类型是 TextSpan ,其它参数同上

  1. const TextSpan({
  2. //样式片段
  3. this.style,
  4. //要显示的文字
  5. this.text,
  6. //样式片段TextSpan数组,可以包含多个TextSpan
  7. this.children,
  8. //用于手势进行识别处理,如点击跳转
  9. this.recognizer,
  10. })

1.5 RichText 示例

拼接字符

  1. Text.rich(TextSpan(
  2. text: 'TextSpan',
  3. style: TextStyle(
  4. color: Colors.red,
  5. fontSize: 24.0,
  6. ),
  7. children: <TextSpan>[
  8. new TextSpan(
  9. text: 'aaaaa',
  10. style: new TextStyle(
  11. color: Colors.blueGrey,
  12. ),
  13. ),
  14. new TextSpan(
  15. text: 'bbbbbb',
  16. style: new TextStyle(
  17. color: Colors.cyan,
  18. ),
  19. ),
  20. ],
  21. )),

添加交互

  1. Text.rich(TextSpan(
  2. children: <TextSpan>[
  3. TextSpan(
  4. text: 'Tap点击',
  5. style: const TextStyle(
  6. color: Colors.blueGrey,
  7. ),
  8. // 点击手势
  9. recognizer: TapGestureRecognizer()
  10. ..onTap = () {
  11. //增加一个点击事件
  12. print('被点击了');
  13. },
  14. ),
  15. ],
  16. )),

2. 导入资源

2.1 加入资源

创建 assets 目录

在更目录下创建 asssets,然后按资源类型,分别创建目录

编辑 pubspec.yaml 文件

  1. # The following section is specific to Flutter.
  2. flutter:
  3. ...
  4. # To add assets to your application, add an assets section, like this:
  5. assets:
  6. - assets/images/
  7. - assets/svgs/
  8. - assets/json/

如果你想整个目录导入可以这样 - assets/images/

只是导入指定图片 - assets/images/abc.png

读取资源

  1. File.json(
  2. 'assets/json/app.json',
  3. ...
  4. )

路径是从 assets 开始,指定文件位置

2.2 加入图片

自动适配屏幕 1x 2x 3x

为了适配不同的屏幕规格,设计了三种分辨率 Flutter 自动适配

目录排列上有个规则, images 目录下是 1x , 2x 3x 分别是单独目录

用猫哥 vscode 插件自动生成

猫哥提供了一个便捷的方式

首先下载插件 <Flutter GetX Generator - 猫哥>

Flutter GetX Generator - 猫哥 - Visual Studio Marketplace

右键自动生成图片,如果已有图片不覆盖

生成资源索引文件

会生成一个 files.txt 文件

创建你自己的资源 dart 文件, 复制下就行

  1. /// 图片资源
  2. class AssetsImages {
  3. static const logoPng = 'assets/images/logo.png';
  4. static const welcomePng = 'assets/images/welcome.png';
  5. static const iconFavouritePng = 'assets/images/icon_favourite.png';
  6. static const iconOffersPng = 'assets/images/icon_offers.png';
  7. static const iconLockPng = 'assets/images/icon_lock.png';
  8. static const iconOrderPng = 'assets/images/icon_order.png';
  9. static const iconMapPng = 'assets/images/icon_map.png';
  10. static const iconPaymentPng = 'assets/images/icon_payment.png';
  11. static const iconUserPng = 'assets/images/icon_user.png';
  12. }

读取图片

  1. ...
  2. Image.asset(
  3. AssetsImages.iconUserPng,
  4. ...
  5. ),

直接用你的 AssetsImages 管理,这样不会应拼写错误造成错误

3. 图片组件 image

Image 是一个图像的 Widget ,提供了一些类方法来快捷使用来自内存、本地、网络、Assets 的图片

下面是入口参数说明

  1. //通过ImageProvider来加载图片
  2. const Image({
  3. Key key,
  4. // ImageProvider,图像显示源
  5. @required this.image,
  6. this.semanticLabel,
  7. this.excludeFromSemantics = false,
  8. //显示宽度
  9. this.width,
  10. //显示高度
  11. this.height,
  12. //图片的混合色值
  13. this.color,
  14. //混合模式
  15. this.colorBlendMode,
  16. //缩放显示模式
  17. this.fit,
  18. //对齐方式
  19. this.alignment = Alignment.center,
  20. //重复方式
  21. this.repeat = ImageRepeat.noRepeat,
  22. //当图片需要被拉伸显示的时候,centerSlice定义的矩形区域会被拉伸,类似.9图片
  23. this.centerSlice,
  24. //类似于文字的显示方向
  25. this.matchTextDirection = false,
  26. //图片发生变化后,加载过程中原图片保留还是留白
  27. this.gaplessPlayback = false,
  28. //图片显示质量
  29. this.filterQuality = FilterQuality.low,
  30. })
  31. // 加载网络图片,封装类:NetworkImage
  32. Image.network(
  33. //路径
  34. String src,
  35. {
  36. Key key,
  37. //缩放
  38. double scale = 1.0,
  39. this.semanticLabel,
  40. this.excludeFromSemantics = false,
  41. this.width,
  42. this.height,
  43. this.color,
  44. this.colorBlendMode,
  45. this.fit,
  46. this.alignment = Alignment.center,
  47. this.repeat = ImageRepeat.noRepeat,
  48. this.centerSlice,
  49. this.matchTextDirection = false,
  50. this.gaplessPlayback = false,
  51. this.filterQuality = FilterQuality.low,
  52. Map<String, String> headers,
  53. })
  54. // 加载本地File文件图片,封装类:FileImage
  55. Image.file(
  56. //File对象
  57. File file,
  58. {
  59. Key key,
  60. double scale = 1.0,
  61. this.semanticLabel,
  62. this.excludeFromSemantics = false,
  63. this.width,
  64. this.height,
  65. this.color,
  66. this.colorBlendMode,
  67. this.fit,
  68. this.alignment = Alignment.center,
  69. this.repeat = ImageRepeat.noRepeat,
  70. this.centerSlice,
  71. this.matchTextDirection = false,
  72. this.gaplessPlayback = false,
  73. this.filterQuality = FilterQuality.low,
  74. })
  75. // 加载本地资源图片,例如项目内资源图片
  76. // 需要把图片路径在pubspec.yaml文件中声明一下,如:
  77. // assets:
  78. // - packages/fancy_backgrounds/backgrounds/background1.png
  79. // 封装类有:AssetImage、ExactAssetImage
  80. Image.asset(
  81. //文件名称,包含路径
  82. String name,
  83. {
  84. Key key,
  85. // 用于访问资源对象
  86. AssetBundle bundle,
  87. this.semanticLabel,
  88. this.excludeFromSemantics = false,
  89. double scale,
  90. this.width,
  91. this.height,
  92. this.color,
  93. this.colorBlendMode,
  94. this.fit,
  95. this.alignment = Alignment.center,
  96. this.repeat = ImageRepeat.noRepeat,
  97. this.centerSlice,
  98. this.matchTextDirection = false,
  99. this.gaplessPlayback = false,
  100. String package,
  101. this.filterQuality = FilterQuality.low,
  102. })
  103. // 加载Uint8List资源图片/从内存中获取图片显示
  104. // 封装类:MemoryImage
  105. Image.memory(
  106. // Uint8List资源图片
  107. Uint8List bytes,
  108. {
  109. Key key,
  110. double scale = 1.0,
  111. this.semanticLabel,
  112. this.excludeFromSemantics = false,
  113. this.width,
  114. this.height,
  115. this.color,
  116. this.colorBlendMode,
  117. this.fit,
  118. this.alignment = Alignment.center,
  119. this.repeat = ImageRepeat.noRepeat,
  120. this.centerSlice,
  121. this.matchTextDirection = false,
  122. this.gaplessPlayback = false,
  123. this.filterQuality = FilterQuality.low,
  124. })

3.1 colorBlendMode 混合参数

枚举 BlendMode 定义

  1. enum BlendMode {
  2. clear,src,dst,srcOver,dstOver,srcIn,dstIn,srcOut,dstOut,srcATop,dstATop,xor,plus,modulate,screen,overlay,darken,lighten,colorDodge,colorBurn,hardLight,softLight,difference,exclusion,multiply,hue,saturation,color,luminosity,
  3. }

效果图

代码

图片色彩 Colors.blue ,混合模式 BlendMode.dstOver

  1. import 'package:flutter/material.dart';
  2. class ImagesPage extends StatelessWidget {
  3. const ImagesPage({Key? key}) : super(key: key);
  4. // BlendMode
  5. Widget _buildBlendMode() {
  6. return Image.asset(
  7. 'assets/images/welcome.png',
  8. color: Colors.blue,
  9. colorBlendMode: BlendMode.dstOver,
  10. );
  11. }
  12. @override
  13. Widget build(BuildContext context) {
  14. return Scaffold(
  15. body: Center(
  16. child: _buildBlendMode(),
  17. ),
  18. );
  19. }
  20. }

输出

可以发现底色蓝色,图片浮在上层

3.2 fit 图片大小适配

BoxFit 枚举定义

代码

  1. import 'package:flutter/material.dart';
  2. class ImagesPage extends StatelessWidget {
  3. const ImagesPage({Key? key}) : super(key: key);
  4. // fit
  5. Widget _buildFit(fit) {
  6. return Column(
  7. children: [
  8. Text("$fit"),
  9. Container(
  10. color: Colors.amber,
  11. child: SizedBox(
  12. width: 200,
  13. height: 100,
  14. child: Image.asset(
  15. 'assets/images/welcome.png',
  16. color: Colors.blue,
  17. colorBlendMode: BlendMode.dstOver,
  18. fit: fit,
  19. ),
  20. ),
  21. ),
  22. ],
  23. );
  24. }
  25. @override
  26. Widget build(BuildContext context) {
  27. return Scaffold(
  28. body: SingleChildScrollView(
  29. child: Center(
  30. child: Column(
  31. children: [
  32. for (var it in BoxFit.values) _buildFit(it),
  33. ],
  34. ),
  35. ),
  36. ),
  37. );
  38. }
  39. }

输出

3.3 ImageProvider 图片对象

Image 组件的 image 参数是一个 ImageProvider, 这样的设计好处是你的图片对象可以来自于各种方式

ImageProvider 是一个抽象类,实现类有 FileImage MemoryImage NetWorkImage

/flutter/lib/src/widgets/image.dart

代码

  1. import 'package:flutter/material.dart';
  2. class ImagesPage extends StatelessWidget {
  3. const ImagesPage({Key? key}) : super(key: key);
  4. // ImageProvider
  5. Widget _buildImageProvider() {
  6. return const Image(
  7. image: AssetImage('assets/images/welcome.png'),
  8. );
  9. }
  10. @override
  11. Widget build(BuildContext context) {
  12. return Scaffold(
  13. body: Center(child: _buildImageProvider()),
  14. );
  15. }
  16. }

输出

4. 图标组件 Icon

Icon 组件用来显示可缩放的图标,不会像图片一样失真,还能设置颜色

4.1 定义

  1. const Icon(
  2. // IconData 图标数据
  3. this.icon, {
  4. Key? key,
  5. // 尺寸
  6. this.size,
  7. // 颜色
  8. this.color,
  9. // 方向
  10. this.textDirection,
  11. this.semanticLabel,
  12. }) : super(key: key);

4.2 开启 pubspec.yaml

  1. # The following section is specific to Flutter.
  2. flutter:
  3. # The following line ensures that the Material Icons font is
  4. # included with your application, so that you can use the icons in
  5. # the material Icons class.
  6. uses-material-design: true

4.3 icon 预览

https://fonts.google.com/icons?selected=Material+Icons

4.4 示例

代码

  1. import 'package:flutter/material.dart';
  2. class IconPage extends StatelessWidget {
  3. const IconPage({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return const Scaffold(
  7. body: Icon(
  8. Icons.campaign,
  9. size: 200,
  10. color: Colors.amber,
  11. ),
  12. );
  13. }
  14. }

输出

4.5 苹果 Icon

苹果风格 icon 需要用 CupertinoIcons 对象来访问

CupertinoIcons class - cupertino library - Dart API

Icon 地图

5. 按钮组件

5.1 ElevatedButton

定义

  1. const ElevatedButton({
  2. Key? key,
  3. // 点击事件
  4. required VoidCallback? onPressed,
  5. // 长按
  6. VoidCallback? onLongPress,
  7. // hover
  8. ValueChanged<bool>? onHover,
  9. ValueChanged<bool>? onFocusChange,
  10. // 样式
  11. ButtonStyle? style,
  12. // 焦点
  13. FocusNode? focusNode,
  14. bool autofocus = false,
  15. Clip clipBehavior = Clip.none,
  16. // 按钮内容
  17. required Widget? child,
  18. })

5.2 ButtonStyle 样式定义

  1. class ButtonStyle with Diagnosticable {
  2. /// Create a [ButtonStyle].
  3. const ButtonStyle({
  4. // 文字
  5. this.textStyle,
  6. // 背景色
  7. this.backgroundColor,
  8. // 前景色
  9. this.foregroundColor,
  10. // 鼠标滑过颜色
  11. this.overlayColor,
  12. // 阴影
  13. this.shadowColor,
  14. // 阴影高度
  15. this.elevation,
  16. // 内边距
  17. this.padding,
  18. // 最小尺寸
  19. this.minimumSize,
  20. // 固定 size
  21. this.fixedSize,
  22. // 最大最小尺寸
  23. this.maximumSize,
  24. // 边框
  25. this.side,
  26. // 形状
  27. this.shape,
  28. // 鼠标光标
  29. this.mouseCursor,
  30. // 紧凑程度
  31. this.visualDensity,
  32. // 配置可以按下按钮的区域的尺寸
  33. this.tapTargetSize,
  34. // 定义 [shape] 和 [elevation] 的动画更改的持续时间
  35. this.animationDuration,
  36. // 检测到的手势是否应该提供声音和/或触觉反馈
  37. this.enableFeedback,
  38. // 子元素对齐方式
  39. this.alignment,
  40. // 墨水效果
  41. this.splashFactory,
  42. });

代码

  1. import 'package:flutter/material.dart';
  2. class ButtonPage extends StatelessWidget {
  3. const ButtonPage({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. body: Center(
  8. child: Column(
  9. mainAxisAlignment: MainAxisAlignment.center,
  10. children: [
  11. // ElevatedButton
  12. ElevatedButton(
  13. onPressed: () {},
  14. child: const Text('ElevatedButton'),
  15. style: ButtonStyle(
  16. // 背景色
  17. backgroundColor: MaterialStateProperty.all(Colors.yellow),
  18. // 前景色
  19. foregroundColor: MaterialStateProperty.all(Colors.red),
  20. // 鼠标滑过颜色
  21. overlayColor: MaterialStateProperty.all(Colors.blue),
  22. // 阴影颜色
  23. shadowColor: MaterialStateProperty.all(Colors.red),
  24. // 阴影高度
  25. elevation: MaterialStateProperty.all(8),
  26. // 边框
  27. side: MaterialStateProperty.all(const BorderSide(
  28. width: 5,
  29. color: Colors.cyan,
  30. )),
  31. // 固定尺寸
  32. fixedSize: MaterialStateProperty.all(const Size(200, 100)),
  33. ),
  34. ),
  35. ],
  36. ),
  37. ),
  38. );
  39. }
  40. }

输出

5.3 其它按钮

  • TextButton 文字按钮
  • OutlinedButton 边框按钮
  • IconButton 图标按钮

代码

  1. import 'package:flutter/material.dart';
  2. class ButtonPage extends StatelessWidget {
  3. const ButtonPage({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. body: Center(
  8. child: Column(
  9. mainAxisAlignment: MainAxisAlignment.center,
  10. children: [
  11. // 文字按钮
  12. TextButton(
  13. onPressed: () {},
  14. child: const Text('TextButton'),
  15. ),
  16. // 边框按钮
  17. OutlinedButton(
  18. onPressed: () {},
  19. child: const Text('OutlinedButton'),
  20. ),
  21. // 图标按钮
  22. IconButton(
  23. onPressed: () {},
  24. icon: const Icon(
  25. Icons.holiday_village,
  26. ),
  27. iconSize: 50,
  28. color: Colors.amber,
  29. ),
  30. // 带图标 TextButton
  31. TextButton.icon(
  32. onPressed: () {},
  33. icon: const Icon(Icons.holiday_village),
  34. label: const Text('带图标 TextButton'),
  35. ),
  36. // 带图标 OutlinedButton
  37. OutlinedButton.icon(
  38. onPressed: () {},
  39. icon: const Icon(Icons.holiday_village),
  40. label: const Text('带图标 OutlinedButton'),
  41. ),
  42. ],
  43. ),
  44. ),
  45. );
  46. }
  47. }

注意 TextButton.icon OutlinedButton.icon 可以输出带图标文字的按钮

输出

6. 路由管理v1 Navigator 

如果对 路由v2 感兴趣的可以去看下面链接, 这里不做讨论 Flutter 导航 Navgiator 2.0 Page Router 说明 -猫哥_哔哩哔哩_bilibili

6.1 匿名路由 

主要是通过 Push() Pop() 来操作路由,简单场景也能满足业务

6.1.1 Navigator 路由管理对象

Navigator是一个路由管理的组件,它提供了打开和退出路由页方

Future push(BuildContext context, Route route) 压入一个新页面到路由堆栈

bool pop(BuildContext context, [ result ]) 压出一个页面出堆栈

6.1.2 MaterialPageRoute 定义

MaterialPageRoute继承自PageRoute类,PageRoute类是一个抽象类,表示占有整个屏幕空间的一个模态路由页面,它还定义了路由构建及切换时过渡动画的相关接口及属性

  1. MaterialPageRoute({
  2. // 是一个WidgetBuilder类型的回调函数,它的作用是构建路由页面的具体内容,返回值是一个widget。我们通常要实现此回调,返回新路由的实例。
  3. WidgetBuilder builder,
  4. // 包含路由的配置信息,如路由名称、是否初始路由(首页)。
  5. RouteSettings settings,
  6. // 默认情况下,当入栈一个新路由时,原来的路由仍然会被保存在内存中,如果想在路由没用的时候释放其所占用的所有资源,可以设置maintainState为 false。
  7. bool maintainState = true,
  8. // 表示新的路由页面是否是一个全屏的模态对话框,在 iOS 中,如果fullscreenDialog为true,新页面将会从屏幕底部滑入(而不是水平方向)。
  9. bool fullscreenDialog = false,
  10. })

6.1.3 路由传值

传递可以在初始新界面对象时通过构造函数压入

新界面退出后的返回值通过 Navigator.pop 的参数返回

6.1.4 示例

首页 NavPaged

  1. import 'package:flutter/material.dart';
  2. class NavPaged extends StatelessWidget {
  3. const NavPaged({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: const Text('NavPaged'),
  9. ),
  10. body: Center(
  11. child: ElevatedButton(
  12. onPressed: () async {
  13. var result = await Navigator.push(
  14. context,
  15. MaterialPageRoute(builder: (context) {
  16. return const DetailPaged(
  17. title: "ducafecat",
  18. );
  19. }),
  20. );
  21. print("路由返回值: $result");
  22. },
  23. child: const Text("Navigator.push DetailPage"),
  24. ),
  25. ),
  26. );
  27. }
  28. }

详情页 DetailPaged

  1. class DetailPaged extends StatelessWidget {
  2. const DetailPaged({Key? key, this.title}) : super(key: key);
  3. // 参数
  4. final String? title;
  5. @override
  6. Widget build(BuildContext context) {
  7. return Scaffold(
  8. appBar: AppBar(
  9. title: const Text('DetailPaged'),
  10. ),
  11. body: Center(
  12. child: Column(
  13. mainAxisAlignment: MainAxisAlignment.center,
  14. children: [
  15. // 按钮
  16. OutlinedButton(
  17. onPressed: () {
  18. Navigator.pop(context, "ok");
  19. },
  20. child: const Text('Back'),
  21. ),
  22. // 显示传值
  23. Text(title ?? ""),
  24. ],
  25. ),
  26. ),
  27. );
  28. }
  29. }

6.2 命名路由

这种方式就优雅了很多,事先定义好路由名字

lib/main.dart

  1. @override
  2. Widget build(BuildContext context) {
  3. return MaterialApp(
  4. ...
  5. routes: {
  6. '/': (context) => const NavPaged(),
  7. '/details': (context) => const DetailPaged(),
  8. },

pushNamed 路由请求, 输入名称即可

  1. onPressed: () async {
  2. var result = await Navigator.pushNamed(
  3. context,
  4. "/details",
  5. arguments: {'title': "ducafecat"},
  6. );
  7. print("路由返回值: $result");
  8. },

取值显示

  1. @override
  2. Widget build(BuildContext context) {
  3. // 取值
  4. final arguments = (ModalRoute.of(context)?.settings.arguments ?? <String, dynamic>{}) as Map;
  5. var title = arguments['title'];
  6. ...
  7. // 显示传值
  8. Text(title ?? ""),

6.3 onGenerateRoute 手动解析

上面的命名路由是好,但是 传参数 不灵活,所以采用 onGenerateRoute 来动态处理

6.3.1 定义路由

lib/main.dart

  1. return MaterialApp(
  2. ...
  3. onGenerateRoute: (settings) {
  4. // Handle '/'
  5. if (settings.name == '/') {
  6. return MaterialPageRoute(builder: (context) => const NavPaged());
  7. }
  8. // Handle '/details/:id'
  9. var uri = Uri.parse(settings.name!);
  10. if (uri.pathSegments.length == 2 &&
  11. uri.pathSegments.first == 'details') {
  12. String uid = uri.pathSegments[1];
  13. return MaterialPageRoute(
  14. builder: (context) => DetailPaged(
  15. uid: uid,
  16. ),
  17. );
  18. }
  19. return MaterialPageRoute(builder: (context) => const UnknownPage());
  20. },

如果没有命中,返回 UnknownPage 界面

6.3.2 导航页完整代码

lib/pages/nav.dart

  1. import 'package:flutter/material.dart';
  2. class NavPaged extends StatelessWidget {
  3. const NavPaged({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: const Text('NavPaged'),
  9. ),
  10. body: Center(
  11. child: ElevatedButton(
  12. onPressed: () async {
  13. var result = await Navigator.pushNamed(
  14. context,
  15. "/details/312312312312",
  16. );
  17. print("路由返回值: $result");
  18. },
  19. child: const Text("Navigator.push DetailPage"),
  20. ),
  21. ),
  22. );
  23. }
  24. }
  25. class DetailPaged extends StatelessWidget {
  26. const DetailPaged({Key? key, this.uid}) : super(key: key);
  27. final String? uid;
  28. @override
  29. Widget build(BuildContext context) {
  30. return Scaffold(
  31. appBar: AppBar(
  32. title: const Text('DetailPaged'),
  33. ),
  34. body: Center(
  35. child: Column(
  36. mainAxisAlignment: MainAxisAlignment.center,
  37. children: [
  38. // 按钮
  39. OutlinedButton(
  40. onPressed: () {
  41. Navigator.pop(context, "ok");
  42. },
  43. child: const Text('Back'),
  44. ),
  45. // 显示传值
  46. Text(uid ?? ""),
  47. ],
  48. ),
  49. ),
  50. );
  51. }
  52. }
  53. class UnknownPage extends StatelessWidget {
  54. const UnknownPage({Key? key}) : super(key: key);
  55. @override
  56. Widget build(BuildContext context) {
  57. return const Scaffold(
  58. body: Text('UnknownPage'),
  59. );
  60. }
  61. }

路由传值

var result = await Navigator.pushNamed( context, "/details/312312312312", );

运行

7. 样式管理

7.1 ThemeData 样式对象

定义

  1. factory ThemeData({
  2. // 全局配置
  3. AndroidOverscrollIndicator? androidOverscrollIndicator,
  4. bool? applyElevationOverlayColor,
  5. NoDefaultCupertinoThemeData? cupertinoOverrideTheme,
  6. InputDecorationTheme? inputDecorationTheme,
  7. MaterialTapTargetSize? materialTapTargetSize,
  8. PageTransitionsTheme? pageTransitionsTheme,
  9. TargetPlatform? platform,
  10. ScrollbarThemeData? scrollbarTheme,
  11. InteractiveInkFeatureFactory? splashFactory,
  12. VisualDensity? visualDensity,
  13. bool? useMaterial3,
  14. // 颜色管理
  15. ColorScheme? colorScheme,
  16. Color? colorSchemeSeed,
  17. Brightness? brightness,
  18. MaterialColor? primarySwatch,
  19. Color? primaryColor,
  20. Color? primaryColorLight,
  21. Color? primaryColorDark,
  22. Color? focusColor,
  23. Color? hoverColor,
  24. Color? shadowColor,
  25. Color? canvasColor,
  26. Color? scaffoldBackgroundColor,
  27. Color? bottomAppBarColor,
  28. Color? cardColor,
  29. Color? dividerColor,
  30. Color? highlightColor,
  31. Color? splashColor,
  32. Color? selectedRowColor,
  33. Color? unselectedWidgetColor,
  34. Color? disabledColor,
  35. Color? secondaryHeaderColor,
  36. Color? backgroundColor,
  37. Color? dialogBackgroundColor,
  38. Color? indicatorColor,
  39. Color? hintColor,
  40. Color? errorColor,
  41. Color? toggleableActiveColor,
  42. // 字体和图标
  43. String? fontFamily,
  44. Typography? typography,
  45. TextTheme? textTheme,
  46. TextTheme? primaryTextTheme,
  47. IconThemeData? iconTheme,
  48. IconThemeData? primaryIconTheme,
  49. // 各种组件样式
  50. AppBarTheme? appBarTheme,
  51. MaterialBannerThemeData? bannerTheme,
  52. BottomAppBarTheme? bottomAppBarTheme,
  53. BottomNavigationBarThemeData? bottomNavigationBarTheme,
  54. BottomSheetThemeData? bottomSheetTheme,
  55. ButtonBarThemeData? buttonBarTheme,
  56. ButtonThemeData? buttonTheme,
  57. CardTheme? cardTheme,
  58. CheckboxThemeData? checkboxTheme,
  59. ChipThemeData? chipTheme,
  60. DataTableThemeData? dataTableTheme,
  61. DialogTheme? dialogTheme,
  62. DividerThemeData? dividerTheme,
  63. DrawerThemeData? drawerTheme,
  64. ElevatedButtonThemeData? elevatedButtonTheme,
  65. FloatingActionButtonThemeData? floatingActionButtonTheme,
  66. ListTileThemeData? listTileTheme,
  67. NavigationBarThemeData? navigationBarTheme,
  68. NavigationRailThemeData? navigationRailTheme,
  69. OutlinedButtonThemeData? outlinedButtonTheme,
  70. PopupMenuThemeData? popupMenuTheme,
  71. ProgressIndicatorThemeData? progressIndicatorTheme,
  72. RadioThemeData? radioTheme,
  73. SliderThemeData? sliderTheme,
  74. SnackBarThemeData? snackBarTheme,
  75. SwitchThemeData? switchTheme,
  76. TabBarTheme? tabBarTheme,
  77. TextButtonThemeData? textButtonTheme,
  78. TextSelectionThemeData? textSelectionTheme,
  79. TimePickerThemeData? timePickerTheme,
  80. ToggleButtonsThemeData? toggleButtonsTheme,
  81. TooltipThemeData? tooltipTheme,

我们在 MaterialApp.theme 中初始

lib/main.dart

  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_application_write_docs/pages/theme.dart';
  3. void main() {
  4. runApp(const MyApp());
  5. }
  6. class MyApp extends StatelessWidget {
  7. const MyApp({Key? key}) : super(key: key);
  8. @override
  9. Widget build(BuildContext context) {
  10. return MaterialApp(
  11. title: 'Flutter Quick Start',
  12. // 样式
  13. theme: ThemeData(
  14. // 主题颜色
  15. primarySwatch: Colors.brown,
  16. // appBar颜色
  17. appBarTheme: ThemeData.light().appBarTheme.copyWith(
  18. backgroundColor: Colors.green,
  19. foregroundColor: Colors.white,
  20. ),
  21. // 按钮颜色
  22. elevatedButtonTheme: ElevatedButtonThemeData(
  23. style: ElevatedButton.styleFrom(
  24. onPrimary: Colors.white,
  25. primary: Colors.amber,
  26. ),
  27. ),
  28. ),
  29. // page
  30. home: const ThemePage(),
  31. // 关闭 debug 标签
  32. debugShowCheckedModeBanner: false,
  33. );
  34. }
  35. }

lib/pages/theme.dart

  1. import 'package:flutter/material.dart';
  2. class ThemePage extends StatelessWidget {
  3. const ThemePage({Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: const Text('ThemePage'),
  9. ),
  10. body: Center(
  11. child: ElevatedButton(
  12. onPressed: () {},
  13. child: const Text('Theme'),
  14. ),
  15. ),
  16. );
  17. }
  18. }

输出

7.2 Color 与 MaterialColor

Color 颜色

Colors class - material library - Dart API

如设计稿的颜色是 #40c254, 转换成 16 进制颜色

  1. // 字符串转 Color
  2. Color stringToColor(String source) {
  3. return Color(int.parse(source, radix: 16) | 0xFF000000);
  4. }
  5. Color c = stringToColor("40c254");

MaterialColor 色彩表

MaterialColor class - material library - Dart API

  1. // 字符串转 MaterialColor
  2. MaterialColor stringToMaterialColor(String source) {
  3. Color color = stringToColor(source);
  4. List<double> strengths = <double>[.05];
  5. Map<int, Color> swatch = <int, Color>{};
  6. final int r = color.red, g = color.green, b = color.blue;
  7. for (int i = 1; i < 10; i++) {
  8. strengths.add(0.1 * i);
  9. }
  10. for (var strength in strengths) {
  11. final double ds = 0.5 - strength;
  12. swatch[(strength * 1000).round()] = Color.fromRGBO(
  13. r + ((ds < 0 ? r : (255 - r)) * ds).round(),
  14. g + ((ds < 0 ? g : (255 - g)) * ds).round(),
  15. b + ((ds < 0 ? b : (255 - b)) * ds).round(),
  16. 1,
  17. );
  18. }
  19. return MaterialColor(color.value, swatch);
  20. }
  21. MaterialColor mc = stringToColor("40c254");

代码

  1. import 'package:flutter/material.dart';
  2. // 字符串转 Color
  3. Color stringToColor(String source) {
  4. return Color(int.parse(source, radix: 16) | 0xFF000000);
  5. }
  6. // 字符串转 MaterialColor
  7. MaterialColor stringToMaterialColor(String source) {
  8. Color color = stringToColor(source);
  9. List<double> strengths = <double>[.05];
  10. Map<int, Color> swatch = <int, Color>{};
  11. final int r = color.red, g = color.green, b = color.blue;
  12. for (int i = 1; i < 10; i++) {
  13. strengths.add(0.1 * i);
  14. }
  15. for (var strength in strengths) {
  16. final double ds = 0.5 - strength;
  17. swatch[(strength * 1000).round()] = Color.fromRGBO(
  18. r + ((ds < 0 ? r : (255 - r)) * ds).round(),
  19. g + ((ds < 0 ? g : (255 - g)) * ds).round(),
  20. b + ((ds < 0 ? b : (255 - b)) * ds).round(),
  21. 1,
  22. );
  23. }
  24. return MaterialColor(color.value, swatch);
  25. }
  26. class ColorPage extends StatelessWidget {
  27. const ColorPage({Key? key}) : super(key: key);
  28. @override
  29. Widget build(BuildContext context) {
  30. var c = stringToColor("FFB822");
  31. var mc = stringToMaterialColor("5C78FF");
  32. return Scaffold(
  33. body: SizedBox.expand(
  34. child: Column(
  35. children: [
  36. // Color
  37. Container(
  38. color: c,
  39. height: 50,
  40. ),
  41. // MaterialColor
  42. for (var i = 1; i < 10; i++)
  43. Container(
  44. color: mc[i * 100],
  45. height: 50,
  46. ),
  47. ],
  48. ),
  49. ),
  50. );
  51. }
  52. }

输出

8. 手势事件

8.1 GestureDetector

GestureDetector是一个用于手势识别的功能性组件,我们通过它可以来识别各种手势

定义

  1. GestureDetector({
  2. Key? key,
  3. this.child,
  4. // 单击
  5. this.onTapDown,
  6. this.onTapUp,
  7. this.onTap,
  8. this.onTapCancel,
  9. // 双指
  10. this.onSecondaryTap,
  11. this.onSecondaryTapDown,
  12. this.onSecondaryTapUp,
  13. this.onSecondaryTapCancel,
  14. // 三点
  15. this.onTertiaryTapDown,
  16. this.onTertiaryTapUp,
  17. this.onTertiaryTapCancel,
  18. // 双击
  19. this.onDoubleTapDown,
  20. this.onDoubleTap,
  21. this.onDoubleTapCancel,
  22. // 长按
  23. this.onLongPressDown,
  24. this.onLongPressCancel,
  25. this.onLongPress,
  26. this.onLongPressStart,
  27. this.onLongPressMoveUpdate,
  28. this.onLongPressUp,
  29. this.onLongPressEnd,
  30. // 两点 三点 长按
  31. this.onSecondaryLongPressDown,
  32. this.onSecondaryLongPressCancel,
  33. this.onSecondaryLongPress,
  34. this.onSecondaryLongPressStart,
  35. this.onSecondaryLongPressMoveUpdate,
  36. this.onSecondaryLongPressUp,
  37. this.onSecondaryLongPressEnd,
  38. this.onTertiaryLongPressDown,
  39. this.onTertiaryLongPressCancel,
  40. this.onTertiaryLongPress,
  41. this.onTertiaryLongPressStart,
  42. this.onTertiaryLongPressMoveUpdate,
  43. this.onTertiaryLongPressUp,
  44. this.onTertiaryLongPressEnd,
  45. // 垂直 水平 Drag
  46. this.onVerticalDragDown,
  47. this.onVerticalDragStart,
  48. this.onVerticalDragUpdate,
  49. this.onVerticalDragEnd,
  50. this.onVerticalDragCancel,
  51. this.onHorizontalDragDown,
  52. this.onHorizontalDragStart,
  53. this.onHorizontalDragUpdate,
  54. this.onHorizontalDragEnd,
  55. this.onHorizontalDragCancel,
  56. this.onForcePressStart,
  57. this.onForcePressPeak,
  58. this.onForcePressUpdate,
  59. this.onForcePressEnd,
  60. // 点击滑动
  61. this.onPanDown,
  62. this.onPanStart,
  63. this.onPanUpdate,
  64. this.onPanEnd,
  65. this.onPanCancel,
  66. this.onScaleStart,
  67. this.onScaleUpdate,
  68. this.onScaleEnd,
  69. this.behavior,
  70. this.excludeFromSemantics = false,
  71. this.dragStartBehavior = DragStartBehavior.start,

包含了大量的交互操作

代码

  1. import 'package:flutter/material.dart';
  2. class GesturePage extends StatefulWidget {
  3. const GesturePage({Key? key}) : super(key: key);
  4. @override
  5. State<GesturePage> createState() => _GesturePageState();
  6. }
  7. class _GesturePageState extends State<GesturePage> {
  8. double? dx, dy;
  9. Widget _buildView() {
  10. return GestureDetector(
  11. child: Container(
  12. color: Colors.amber,
  13. width: 200,
  14. height: 200,
  15. ),
  16. // 点击
  17. onTap: () {
  18. print('点击 onTap');
  19. },
  20. // 长按
  21. onLongPress: () {
  22. print('长按 onLongPress');
  23. },
  24. // 双击
  25. onDoubleTap: () {
  26. print('双击 onLongPress');
  27. },
  28. // 按下
  29. onPanDown: (DragDownDetails e) {
  30. print("按下 ${e.globalPosition}");
  31. },
  32. // 按下滑动
  33. onPanUpdate: (DragUpdateDetails e) {
  34. setState(() {
  35. dx = e.delta.dx;
  36. dy = e.delta.dy;
  37. });
  38. },
  39. // 松开
  40. onPanEnd: (DragEndDetails e) {
  41. print(e.velocity);
  42. },
  43. );
  44. }
  45. @override
  46. Widget build(BuildContext context) {
  47. return Scaffold(
  48. body: SizedBox.expand(
  49. child: Column(
  50. mainAxisAlignment: MainAxisAlignment.center,
  51. children: [
  52. _buildView(),
  53. // 显示
  54. Text('x: $dx, y: $dy'),
  55. ],
  56. ),
  57. ),
  58. );
  59. }
  60. }

输出

  1. flutter: 用户手指按下:Offset(127.7, 218.0)
  2. flutter: Velocity(0.0, 0.0)
  3. Reloaded 1 of 585 libraries in 171ms.
  4. Reloaded 2 of 585 libraries in 205ms.
  5. flutter: 按下 Offset(128.0, 188.2)
  6. flutter: 长按 onLongPress
  7. flutter: 按下 Offset(145.0, 214.2)
  8. flutter: Velocity(-44.4, -45.0)

8.2 InkWell

InkWell 是带有水波纹的点击事件的组件

定义

  1. const InkWell({
  2. Key? key,
  3. Widget? child,
  4. // 点击
  5. GestureTapCallback? onTap,
  6. GestureTapCallback? onDoubleTap,
  7. // 长按
  8. GestureLongPressCallback? onLongPress,
  9. GestureTapDownCallback? onTapDown,
  10. GestureTapCancelCallback? onTapCancel,
  11. ValueChanged<bool>? onHighlightChanged,
  12. ValueChanged<bool>? onHover,
  13. // 光标样式
  14. MouseCursor? mouseCursor,
  15. // 颜色
  16. Color? focusColor,
  17. Color? hoverColor,
  18. Color? highlightColor,
  19. MaterialStateProperty<Color?>? overlayColor,
  20. Color? splashColor,
  21. InteractiveInkFeatureFactory? splashFactory,
  22. double? radius,
  23. BorderRadius? borderRadius,
  24. ShapeBorder? customBorder,
  25. bool? enableFeedback = true,
  26. bool excludeFromSemantics = false,
  27. FocusNode? focusNode,
  28. bool canRequestFocus = true,
  29. ValueChanged<bool>? onFocusChange,
  30. bool autofocus = false,
  31. })

代码

  1. import 'package:flutter/material.dart';
  2. class InkWellPage extends StatelessWidget {
  3. const InkWellPage({Key? key}) : super(key: key);
  4. Widget _buildView() {
  5. return InkWell(
  6. // 点击
  7. onTap: () {},
  8. // 水波纹颜色
  9. splashColor: Colors.blue,
  10. // 高亮颜色
  11. highlightColor: Colors.yellow,
  12. // 鼠标滑过颜色
  13. hoverColor: Colors.brown,
  14. //
  15. child: const Text(
  16. '点我 InkWell',
  17. style: TextStyle(
  18. fontSize: 50,
  19. ),
  20. ),
  21. );
  22. }
  23. @override
  24. Widget build(BuildContext context) {
  25. return Scaffold(
  26. body: Center(
  27. child: _buildView(),
  28. ),
  29. );
  30. }
  31. }

输出

9. 输入框 TextField

TextField用于文本输入, 有着丰富的属性,定义如下

9.1 定义

  1. const TextField({
  2. Key? key,
  3. // 控制器
  4. this.controller,
  5. // 焦点管理
  6. this.focusNode,
  7. // 装饰器 背景 颜色 边框 ...
  8. this.decoration = const InputDecoration(),
  9. // 键盘输入类型
  10. // text 文本输入键盘
  11. // multiline 多行文本,需和maxLines配合使用(设为null或大于1)
  12. // number 数字;会弹出数字键盘
  13. // phone 优化后的电话号码输入键盘;会弹出数字键盘并显示“* #”
  14. // datetime 优化后的日期输入键盘;Android上会显示“: -”
  15. // emailAddress 优化后的电子邮件地址;会显示“@ .”
  16. // url 优化后的url输入键盘; 会显示“/ .”
  17. TextInputType? keyboardType,
  18. // 键盘动作按钮图标
  19. // TextInputAction.search 搜索
  20. this.textInputAction,
  21. this.textCapitalization = TextCapitalization.none,
  22. // 正在编辑的文本样式
  23. this.style,
  24. this.strutStyle,
  25. // 输入框内编辑文本在水平方向的对齐方式
  26. this.textAlign = TextAlign.start,
  27. this.textAlignVertical,
  28. // 文字反向
  29. this.textDirection,
  30. // 只读
  31. this.readOnly = false,
  32. ToolbarOptions? toolbarOptions,
  33. // 显示光标
  34. this.showCursor,
  35. // 自动焦点
  36. this.autofocus = false,
  37. // 密文显示
  38. this.obscuringCharacter = '•',
  39. this.obscureText = false,
  40. this.autocorrect = true,
  41. SmartDashesType? smartDashesType,
  42. SmartQuotesType? smartQuotesType,
  43. // 启用提示
  44. this.enableSuggestions = true,
  45. // 输入框的最大行数,默认为1;如果为null,则无行数限制。
  46. this.maxLines = 1,
  47. this.minLines,
  48. this.expands = false,
  49. // 代表输入框文本的最大长度,设置后输入框右下角会显示输入的文本计数。
  50. this.maxLength,
  51. @Deprecated(
  52. 'Use maxLengthEnforcement parameter which provides more specific '
  53. 'behavior related to the maxLength limit. '
  54. 'This feature was deprecated after v1.25.0-5.0.pre.',
  55. )
  56. this.maxLengthEnforced = true,
  57. this.maxLengthEnforcement,
  58. // 输入框内容改变时的回调函数;注:内容改变事件也可以通过controller来监听。
  59. this.onChanged,
  60. // 编辑完成
  61. this.onEditingComplete,
  62. // 确认输入内容
  63. this.onSubmitted,
  64. this.onAppPrivateCommand,
  65. // 指定输入格式;当用户输入内容改变时,会根据指定的格式来校验。
  66. this.inputFormatters,
  67. // 如果为false,则输入框会被禁用,禁用状态不接收输入和事件,同时显示禁用态样式(在其decoration中定义)。
  68. this.enabled,
  69. // 光标样式
  70. // 自定义输入框光标宽度、圆角和颜色
  71. this.cursorWidth = 2.0,
  72. this.cursorHeight,
  73. this.cursorRadius,
  74. this.cursorColor,
  75. this.selectionHeightStyle = ui.BoxHeightStyle.tight,
  76. this.selectionWidthStyle = ui.BoxWidthStyle.tight,
  77. this.keyboardAppearance,
  78. this.scrollPadding = const EdgeInsets.all(20.0),
  79. this.dragStartBehavior = DragStartBehavior.start,
  80. this.enableInteractiveSelection = true,
  81. this.selectionControls,
  82. // 点击
  83. this.onTap,
  84. // 鼠标
  85. this.mouseCursor,
  86. this.buildCounter,
  87. this.scrollController,
  88. this.scrollPhysics,
  89. this.autofillHints = const <String>[],
  90. this.clipBehavior = Clip.hardEdge,
  91. this.restorationId,
  92. this.enableIMEPersonalizedLearning = true,
  93. })

9.2 示例

代码

  1. import 'package:flutter/material.dart';
  2. class InputPage extends StatefulWidget {
  3. const InputPage({Key? key}) : super(key: key);
  4. @override
  5. State<InputPage> createState() => _InputPageState();
  6. }
  7. class _InputPageState extends State<InputPage> {
  8. // 文本消息
  9. String _message = "";
  10. // 输入框控制器
  11. final TextEditingController _controllerName = TextEditingController();
  12. final TextEditingController _controllerPassword = TextEditingController();
  13. // 管理焦点
  14. FocusNode focusNodeName = FocusNode();
  15. FocusNode focusNodePassword = FocusNode();
  16. FocusScopeNode? focusScopeNode;
  17. // 输入框 - 用户名
  18. Widget _buildName() {
  19. return TextField(
  20. // 控制器
  21. controller: _controllerName,
  22. // 焦点
  23. autofocus: true,
  24. // 焦点管理
  25. focusNode: focusNodeName,
  26. // 输入框的样式
  27. decoration: const InputDecoration(
  28. labelText: '用户名',
  29. hintText: '请输入',
  30. prefixIcon: Icon(Icons.person),
  31. suffixIcon: Icon(Icons.edit),
  32. border: OutlineInputBorder(),
  33. ),
  34. // 输入改变事件
  35. onChanged: (String value) {
  36. setState(() {
  37. _message = value;
  38. });
  39. },
  40. // 提交回车事件
  41. onSubmitted: (String value) {
  42. focusScopeNode ??= FocusScope.of(context);
  43. focusScopeNode?.requestFocus(focusNodePassword);
  44. },
  45. );
  46. }
  47. // 输入框 - 密码
  48. Widget _buildPassword() {
  49. return TextField(
  50. controller: _controllerPassword,
  51. // 密码显示
  52. obscureText: true,
  53. // 焦点管理
  54. focusNode: focusNodePassword,
  55. // 输入框的样式
  56. decoration: const InputDecoration(
  57. labelText: '密码',
  58. hintText: '请输入',
  59. prefixIcon: Icon(Icons.person),
  60. suffixIcon: Icon(Icons.edit),
  61. border: OutlineInputBorder(),
  62. ),
  63. );
  64. }
  65. // 按钮
  66. Widget _buildButton() {
  67. return ElevatedButton(
  68. child: const Text('登录 Now!'),
  69. onPressed: () {
  70. setState(() {
  71. _message =
  72. 'name:${_controllerName.text}, pass:${_controllerPassword.text}';
  73. });
  74. },
  75. );
  76. }
  77. // 显示
  78. Widget _buildMessage() {
  79. return Text(_message);
  80. }
  81. @override
  82. void dispose() {
  83. // 释放控制器
  84. _controllerName.dispose();
  85. _controllerPassword.dispose();
  86. super.dispose();
  87. }
  88. @override
  89. Widget build(BuildContext context) {
  90. return Scaffold(
  91. body: Padding(
  92. padding: const EdgeInsets.all(8.0),
  93. child: Column(
  94. children: [
  95. _buildName(),
  96. const SizedBox(height: 10),
  97. _buildPassword(),
  98. const SizedBox(height: 10),
  99. _buildButton(),
  100. const SizedBox(height: 10),
  101. _buildMessage(),
  102. ],
  103. ),
  104. ),
  105. );
  106. }
  107. }

输出

创作不易,希望读者三连支持 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/913649
推荐阅读
相关标签