【Flutter】StatefulWidget 组件 ( Image 组件 | TextField 组件 )

简介: 【Flutter】StatefulWidget 组件 ( Image 组件 | TextField 组件 )

文章目录

一、Image 组件

二、TextField 组件

三、 相关资源





一、Image 组件


Image 组件有多个命名构造函数 , 可以从 文件 / 内存 / 网络 / Assets 中加载文件 , 分别对应不同的构造函数 ;


class Image extends StatefulWidget {
  // 从网络中加载图片的构造函数 
  Image.network(
    // 图片的网络地址
    String src,  {
    Key key,
    double scale = 1.0,
    this.frameBuilder,
    this.loadingBuilder,
    this.errorBuilder,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width, // 组件宽度
    this.height, // 组件高度
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.filterQuality = FilterQuality.low,
    this.isAntiAlias = false,
    Map<String, String> headers,
    int cacheWidth,
    int cacheHeight,
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, NetworkImage(src, scale: scale, headers: headers)),
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
       assert(isAntiAlias != null),
       super(key: key);
  // 从文件中加载图片的构造函数 
  Image.file(
    File file, {
    Key key,
    double scale = 1.0,
    this.frameBuilder,
    this.errorBuilder,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.isAntiAlias = false,
    this.filterQuality = FilterQuality.low,
    int cacheWidth,
    int cacheHeight,
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
       loadingBuilder = null,
       assert(alignment != null),
       assert(repeat != null),
       assert(filterQuality != null),
       assert(matchTextDirection != null),
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
       assert(isAntiAlias != null),
       super(key: key);
  // 从 Assets 资源文件中加载图片
  Image.asset()
  // 从内存中加载图片的构造函数
  Image.memory()
}


图片组件使用示例 :


               

// 图片组件 , 从网络中加载一张图片
                    Image.network(
                        // 图片地址
                      "https://ucc.alicdn.com/images/user-upload-01/20210228180808133.png",
                      // 图片宽度
                      width: 200,
                      // 图片高度
                      height: 200,
                    ),


完整代码示例 :


import 'package:flutter/material.dart';
class StatefulWidgetPage extends StatefulWidget {
  @override
  _StatefulWidgetPageState createState() => _StatefulWidgetPageState();
}
class _StatefulWidgetPageState extends State<StatefulWidgetPage> {
  /// 当前被选中的底部导航栏索引
  int _currentSelectedIndex = 0;
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 文本组件样式 , 可以设置给 Text 文本组件
    // 设置字体大小 20, 颜色红色
    TextStyle textStyle = TextStyle(fontSize: 20, color: Colors.red);
    return MaterialApp(
      title: 'StatefulWidgetPage 组件示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        // 顶部标题栏
        appBar: AppBar(title: Text('StatefulWidgetPage 组件示例'),),
        // 底部导航栏 BottomNavigationBar 设置
        // items 可以设置多个 BottomNavigationBarItem
        bottomNavigationBar: BottomNavigationBar(
          // 设置当前选中的底部导航索引
          currentIndex: _currentSelectedIndex,
          // 设置点击底部导航栏的回调事件 , index 参数是点击的索引值
          onTap: (index){
            // 回调 StatefulWidget 组件的 setState 设置状态的方法 , 修改当前选中索引
            // 之后 BottomNavigationBar 组件会自动更新当前选中的选项卡
            setState(() {
              // 改变 int _currentSelectedIndex 变量的状态
              _currentSelectedIndex = index;
            });
          },
          // 条目
          items: [
          // 设置底部导航栏条目, 每个条目可以设置一个图标
          BottomNavigationBarItem(
            // 默认状态下的图标
            icon: Icon(Icons.home, color: Colors.grey,),
            // 激活状态下的图标
            activeIcon: Icon(Icons.home, color: Colors.red,),
            // 设置标题
            title: Text("主页")
          ),
          // 设置底部导航栏条目, 每个条目可以设置一个图标
          BottomNavigationBarItem(
            // 默认状态下的图标
            icon: Icon(Icons.settings, color: Colors.grey,),
            // 激活状态下的图标
            activeIcon: Icon(Icons.settings, color: Colors.red,),
              // 设置标题
              title: Text("设置")
          )
        ],),
        // 设置悬浮按钮
        floatingActionButton: FloatingActionButton(
          onPressed: (){
            print("悬浮按钮点击");
          },
          child: Text("悬浮按钮组件"),
        ),
        // Container 容器使用
        body:
        _currentSelectedIndex == 0 ?
        // 刷新指示器组件
        RefreshIndicator(
          // 显示的内容
          child: ListView(
            children: <Widget>[
              Container( // 对应底部导航栏设置选项卡
                // 设置容器的装饰器 , BoxDecoration 是最常用的装饰器
                // 可以自行查看 BoxDecoration 中可以设置的属性
                decoration: BoxDecoration(color: Colors.white),
                // 设置 child 子组件居中方式, 居中放置
                alignment: Alignment.center,
                // 子组件, 子组件设置为一个 Column 组件
                child: Column(
                  // Column 子组件, 这里设置 Text 文本组件
                  children: <Widget>[
                    Text("主页面选项卡, 下拉刷新"),
                    // 图片组件 , 从网络中加载一张图片
                    Image.network(
                        // 图片地址
                      "https://ucc.alicdn.com/images/user-upload-01/20210228180808133.png",
                      // 图片宽度
                      width: 200,
                      // 图片高度
                      height: 200,
                    ),
                  ],
                ),
              ),
            ],
          ),
          // 刷新时回调的方法
          // 列表发生下拉操作时, 回调该方法
          // 该回调是 Future 类型的
          onRefresh: _refreshIndicatorOnRefresh,
        )
        :
        Container( // 对应底部导航栏设置选项卡
          // 设置容器的装饰器 , BoxDecoration 是最常用的装饰器
          // 可以自行查看 BoxDecoration 中可以设置的属性
          decoration: BoxDecoration(color: Colors.white),
          // 设置 child 子组件居中方式, 居中放置
          alignment: Alignment.center,
          // 子组件, 子组件设置为一个 Column 组件
          child: Column(
            // Column 子组件, 这里设置 Text 文本组件
            children: <Widget>[
              Text("设置页面选项卡")
            ],
          ),
        ) , // 该设置与 _currentSelectedIndex == 0? 相对应, ?: 三目运算符
      ),
    );
  }
  /// RefreshIndicator 发生下拉操作时, 回调该方法
  /// 该方啊是一个异步方法 , 在方法体前添加 async 关键字
  Future<Null> _refreshIndicatorOnRefresh() async{
    // 暂停 500 ms , 使用 await 关键字实现
    // 在这 500 ms 之间 , 列表处于刷新状态
    // 500 ms 之后 , 列表变为非刷新状态
    await Future.delayed(Duration(milliseconds: 500));
    return null;
  }
}


运行效果展示 :


image.png






二、TextField 组件


TextField 组件构造函数的可选参数 : 下面代码中的可选参数就是 TextField 组件可以设置的参数选项 ;


class TextField extends StatefulWidget {
  const TextField({
    Key key,
    this.controller,
    this.focusNode,
    this.decoration = const InputDecoration(),
    TextInputType keyboardType,
    this.textInputAction,
    this.textCapitalization = TextCapitalization.none,
    this.style,
    this.strutStyle,
    this.textAlign = TextAlign.start,
    this.textAlignVertical,
    this.textDirection,
    this.readOnly = false,
    ToolbarOptions toolbarOptions,
    this.showCursor,
    this.autofocus = false,
    this.obscuringCharacter = '•',
    this.obscureText = false,
    this.autocorrect = true,
    SmartDashesType smartDashesType,
    SmartQuotesType smartQuotesType,
    this.enableSuggestions = true,
    this.maxLines = 1,
    this.minLines,
    this.expands = false,
    this.maxLength,
    this.maxLengthEnforced = true,
    this.onChanged,
    this.onEditingComplete,
    this.onSubmitted,
    this.onAppPrivateCommand,
    this.inputFormatters,
    this.enabled,
    this.cursorWidth = 2.0,
    this.cursorHeight,
    this.cursorRadius,
    this.cursorColor,
    this.selectionHeightStyle = ui.BoxHeightStyle.tight,
    this.selectionWidthStyle = ui.BoxWidthStyle.tight,
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0),
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,
    this.onTap,
    this.mouseCursor,
    this.buildCounter,
    this.scrollController,
    this.scrollPhysics,
    this.autofillHints,
    this.restorationId,
  })
}


输入框组件代码示例 :


                 

// 输入框组件
                    TextField(
                      // 设置输入框样式
                      decoration: InputDecoration(
                        // 设置内容边距, 左右边距为 10, 上下边距为 0
                        contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        // 设置的提示文案信息
                        hintText: "提示信息",
                        // 设置提示文案样式
                        hintStyle: TextStyle(fontSize: 20, color: Colors.grey),
                      ),


完整代码示例 :


import 'package:flutter/material.dart';
class StatefulWidgetPage extends StatefulWidget {
  @override
  _StatefulWidgetPageState createState() => _StatefulWidgetPageState();
}
class _StatefulWidgetPageState extends State<StatefulWidgetPage> {
  /// 当前被选中的底部导航栏索引
  int _currentSelectedIndex = 0;
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 文本组件样式 , 可以设置给 Text 文本组件
    // 设置字体大小 20, 颜色红色
    TextStyle textStyle = TextStyle(fontSize: 20, color: Colors.red);
    return MaterialApp(
      title: 'StatefulWidgetPage 组件示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        // 顶部标题栏
        appBar: AppBar(title: Text('StatefulWidgetPage 组件示例'),),
        // 底部导航栏 BottomNavigationBar 设置
        // items 可以设置多个 BottomNavigationBarItem
        bottomNavigationBar: BottomNavigationBar(
          // 设置当前选中的底部导航索引
          currentIndex: _currentSelectedIndex,
          // 设置点击底部导航栏的回调事件 , index 参数是点击的索引值
          onTap: (index){
            // 回调 StatefulWidget 组件的 setState 设置状态的方法 , 修改当前选中索引
            // 之后 BottomNavigationBar 组件会自动更新当前选中的选项卡
            setState(() {
              // 改变 int _currentSelectedIndex 变量的状态
              _currentSelectedIndex = index;
            });
          },
          // 条目
          items: [
          // 设置底部导航栏条目, 每个条目可以设置一个图标
          BottomNavigationBarItem(
            // 默认状态下的图标
            icon: Icon(Icons.home, color: Colors.grey,),
            // 激活状态下的图标
            activeIcon: Icon(Icons.home, color: Colors.red,),
            // 设置标题
            title: Text("主页")
          ),
          // 设置底部导航栏条目, 每个条目可以设置一个图标
          BottomNavigationBarItem(
            // 默认状态下的图标
            icon: Icon(Icons.settings, color: Colors.grey,),
            // 激活状态下的图标
            activeIcon: Icon(Icons.settings, color: Colors.red,),
              // 设置标题
              title: Text("设置")
          )
        ],),
        // 设置悬浮按钮
        floatingActionButton: FloatingActionButton(
          onPressed: (){
            print("悬浮按钮点击");
          },
          child: Text("悬浮按钮组件"),
        ),
        // Container 容器使用
        body:
        _currentSelectedIndex == 0 ?
        // 刷新指示器组件
        RefreshIndicator(
          // 显示的内容
          child: ListView(
            children: <Widget>[
              Container( // 对应底部导航栏设置选项卡
                // 设置容器的装饰器 , BoxDecoration 是最常用的装饰器
                // 可以自行查看 BoxDecoration 中可以设置的属性
                decoration: BoxDecoration(color: Colors.white),
                // 设置 child 子组件居中方式, 居中放置
                alignment: Alignment.center,
                // 子组件, 子组件设置为一个 Column 组件
                child: Column(
                  // Column 子组件, 这里设置 Text 文本组件
                  children: <Widget>[
                    Text("主页面选项卡, 下拉刷新"),
                    // 图片组件 , 从网络中加载一张图片
                    Image.network(
                        // 图片地址
                      "https://ucc.alicdn.com/images/user-upload-01/20210228180808133.png",
                      // 图片宽度
                      width: 200,
                      // 图片高度
                      height: 200,
                    ),
                    // 输入框组件
                    TextField(
                      // 设置输入框样式
                      decoration: InputDecoration(
                        // 设置内容边距, 左右边距为 10, 上下边距为 0
                        contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        // 设置的提示文案信息
                        hintText: "提示信息",
                        // 设置提示文案样式
                        hintStyle: TextStyle(fontSize: 20, color: Colors.grey),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
          // 刷新时回调的方法
          // 列表发生下拉操作时, 回调该方法
          // 该回调是 Future 类型的
          onRefresh: _refreshIndicatorOnRefresh,
        )
        :
        Container( // 对应底部导航栏设置选项卡
          // 设置容器的装饰器 , BoxDecoration 是最常用的装饰器
          // 可以自行查看 BoxDecoration 中可以设置的属性
          decoration: BoxDecoration(color: Colors.white),
          // 设置 child 子组件居中方式, 居中放置
          alignment: Alignment.center,
          // 子组件, 子组件设置为一个 Column 组件
          child: Column(
            // Column 子组件, 这里设置 Text 文本组件
            children: <Widget>[
              Text("设置页面选项卡")
            ],
          ),
        ) , // 该设置与 _currentSelectedIndex == 0? 相对应, ?: 三目运算符
      ),
    );
  }
  /// RefreshIndicator 发生下拉操作时, 回调该方法
  /// 该方啊是一个异步方法 , 在方法体前添加 async 关键字
  Future<Null> _refreshIndicatorOnRefresh() async{
    // 暂停 500 ms , 使用 await 关键字实现
    // 在这 500 ms 之间 , 列表处于刷新状态
    // 500 ms 之后 , 列表变为非刷新状态
    await Future.delayed(Duration(milliseconds: 500));
    return null;
  }
}


运行效果展示 :


image.png






三、 相关资源


参考资料 :


Flutter 官网 : https://flutter.dev/

Flutter 开发文档 : https://flutter.cn/docs ( 强烈推荐 )

官方 GitHub 地址 : https://github.com/flutter

Flutter 中文社区 : https://flutter.cn/

Flutter 实用教程 : https://flutter.cn/docs/cookbook

Flutter CodeLab : https://codelabs.flutter-io.cn/

Dart 中文文档 : https://dart.cn/

Dart 开发者官网 : https://api.dart.dev/

Flutter 中文网 ( 非官方 , 翻译的很好 ) : https://flutterchina.club/ , http://flutter.axuer.com/docs/

Flutter 相关问题 : https://flutterchina.club/faq/ ( 入门阶段推荐看一遍 )


博客源码下载 :


GitHub 地址 : https://github.com/han1202012/flutter_cmd ( 随博客进度一直更新 , 有可能没有本博客的源码 )


博客源码快照 : https://download.csdn.net/download/han1202012/15500147 ( 本篇博客的源码快照 , 可以找到本博客的源码 )


目录
相关文章
|
1月前
Flutter 组件(二)文本 与 输入框组件
Flutter 组件(二)文本 与 输入框组件
137 0
|
1月前
|
容器
Flutter 组件(一)组件概述
Flutter 组件(一)组件概述
69 0
|
1月前
|
设计模式 JavaScript 前端开发
flutter组件封装技巧
工厂函数不会自动调用,需要手动调用
28 3
|
1月前
|
Dart
Flutter 中优雅切换应用主题的组件
【Flutter】使用adaptive_theme组件优雅切换应用主题:封装MaterialApp,支持light/dark/system模式,自定义色彩,保存选择,含调试按钮。安装配置、设置主题、监听切换、自定义颜色、读取配置步骤详细。代码示例与学习路径推荐。[查看完整教程](https://flutter.ducafecat.com/blog/flutter-app-theme-switch)
Flutter 中优雅切换应用主题的组件
|
1月前
|
前端开发 搜索推荐 UED
【Flutter前端技术开发专栏】Flutter中的高级UI组件应用
【4月更文挑战第30天】探索Flutter的高级UI组件,如`TabBar`、`Drawer`、`BottomSheet`,提升应用体验和美观度。使用高级组件能节省开发时间,提供内置交互逻辑和优秀视觉效果。示例代码展示了如何实现底部导航栏、侧边导航和底部弹出菜单。同时,自定义组件允许个性化设计和功能扩展,但也带来性能优化和维护挑战。参考Flutter官方文档和教程,深入学习并有效利用这些组件。
【Flutter前端技术开发专栏】Flutter中的高级UI组件应用
|
9月前
|
人机交互
Flutter笔记 - ListTile组件及其应用
Flutter笔记 - ListTile组件及其应用
138 0
|
1月前
|
开发者 索引 容器
Flutter开发笔记:Flutter 布局相关组件
Flutter开发笔记:Flutter 布局相关组件
168 0
|
1月前
|
iOS开发
Flutter 组件(三)按钮类组件
Flutter 组件(三)按钮类组件
215 0
|
1月前
Flutter StatefulWidget传递数据,多级控件传递数据
Flutter StatefulWidget传递数据,多级控件传递数据 在Flutter中,StatefulWidget可以通过构造函数将数据传递给其子控件,这种方式适用于一些简单的场景。但是,当存在多级嵌套控件时,将数据从祖先传递到后代可能会变得困难。在这种情况下,可以使用Flutter提供的InheritedWidget类来传递数据。
|
8月前
|
API 开发者 索引
Flutter笔记:发布一个多功能轮播组件 awesome_carousel
awesome_carousel 模块是一个Flutter轮播图模块。可以实现包括自定义指示器、动画、滚动等等众多功能。能够指定相当多地细节(可以参考 API 部分了解)本文给出 awesome_carousel 模块的两个简单的用法示例。
121 0