Flutter_学习记录_基本组件的使用记录

1.TextWidge的常用属性

1.1TextAlign: 文本对齐属性

常用的样式有:

  • TextAlign.center 居中
  • TextAlign.left 左对齐
  • TextAlign.right 有对齐

使用案例:

bash 复制代码
body: Center(
          child: Text(
            '开启 TextWidget 的旅程吧,珠珠, 开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠',
            textAlign: TextAlign.center),
        )

1.2 maxLines: 文本显示的最大行数

使用案例:

bash 复制代码
body: Center(
          child: Text(
            '开启 TextWidget 的旅程吧,珠珠, 开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠',
            textAlign: TextAlign.center,
            maxLines: 2
        )

1.3 overFlow: 控制文本的溢出效果

常用的样式有:

  • TextOverflow.clip 直接截断
  • TextOverflow.ellipsis 被截断后,末尾处用... 来表示
  • TextOverflow.fade 最后一行有个阴影

使用案例:

bash 复制代码
body: Center(
          child: Text(
            '开启 TextWidget 的旅程吧,珠珠, 开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠开启 TextWidget 的旅程吧,珠珠',
            textAlign: TextAlign.center,
            maxLines: 2,
            overflow: TextOverflow.ellipsis),
        )

1.4 style 样式

style 给文本添加样式,需要用到组件TextStyle, 查看TextStyle 的定义如下:

cpp 复制代码
 const TextStyle({
    this.inherit = true,
    this.color,
    this.backgroundColor,
    this.fontSize,
    this.fontWeight,
    this.fontStyle,
    this.letterSpacing,
    this.wordSpacing,
    this.textBaseline,
    this.height,
    this.leadingDistribution,
    this.locale,
    this.foreground,
    this.background,
    this.shadows,
    this.fontFeatures,
    this.fontVariations,
    this.decoration,
    this.decorationColor,
    this.decorationStyle,
    this.decorationThickness,
    this.debugLabel,
    String? fontFamily,
    List<String>? fontFamilyFallback,
    String? package,
    this.overflow,
  }

使用案例:

cpp 复制代码
body: Center(
          child: Text(
            '开启 TextWidget 的旅程吧,珠珠',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 25.0,
              color: Color.fromARGB(255, 255, 150, 150),
              decoration: TextDecoration.underline,
              decorationStyle: TextDecorationStyle.solid
            ),),
        )

2. Container 容器组件

2.1 Alignment 属性的使用

常用样式:

/// The top left corner.

static const Alignment topLeft = Alignment(-1.0, -1.0);

/// The center point along the top edge.

static const Alignment topCenter = Alignment(0.0, -1.0);

/// The top right corner.

static const Alignment topRight = Alignment(1.0, -1.0);

/// The center point along the left edge.

static const Alignment centerLeft = Alignment(-1.0, 0.0);

/// The center point, both horizontally and vertically.

static const Alignment center = Alignment(0.0, 0.0);

/// The center point along the right edge.

static const Alignment centerRight = Alignment(1.0, 0.0);

/// The bottom left corner.

static const Alignment bottomLeft = Alignment(-1.0, 1.0);

/// The center point along the bottom edge.

static const Alignment bottomCenter = Alignment(0.0, 1.0);

/// The bottom right corner.

static const Alignment bottomRight = Alignment(1.0, 1.0);

2.2 设置宽高和颜色

高: height

宽:width

背景色:color

2.3 Padding 内边距属性的使用

两种设置方式:

  • EdgeInsets.all(xx) 上下左右的内边距统一设置
  • EdgeInsets.fromLTRB(left, top, right, bottom) 上下左右单独设置

2.4 margin外边距属性的使用

两种设置方式:

  • EdgeInsets.all(xx) 上下左右的内边距统一设置
  • EdgeInsets.fromLTRB(left, top, right, bottom) 上下左右单独设置

2.5 decoration 属性制作彩色背景

需要使用组件BoxDecoration 来设置

dart 复制代码
decoration: BoxDecoration(
              gradient: const LinearGradient(colors: [
                Colors.lightBlue,
                Colors.greenAccent,
                Colors.purple
              ])
            )

2.5 使用案例

dart 复制代码
body: Center(
          child: Container(
            alignment: Alignment.topLeft,
            width: 500.0,
            height: 300.0,
            // color: Colors.lightBlue,
            padding: const EdgeInsets.fromLTRB(50, 20, 10, 30), // 上下左右边距都一样的
            margin: const EdgeInsets.all(10.0),
            decoration: BoxDecoration(
              gradient: const LinearGradient(colors: [
                Colors.lightBlue,
                Colors.greenAccent,
                Colors.purple
              ])
            ),
            child: Text(
              '开启 TextWidget 的旅程吧,珠珠',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 45.0,
                color: Color.fromARGB(255, 255, 150, 150),
                decoration: TextDecoration.underline,
                decorationStyle: TextDecorationStyle.solid
              ),
            ),
          ),
        )
        

3. Image图片组件的使用

3.1 Image Widget的集中加入形式

  1. Image.asset: 加载资源图片,会使打包时包体积过大
  2. Image.network: 网络资源图片,经常换的或者动态图片
  3. Image.file: 本地图片,比如相机照相后的图片预览

3.2 Fit 属性的使用

Fit 属性是说图片平铺的效果设置,用BoxFit组件来设置,主要有这几种样式:

  1. BoxFit.fill: 填充整个图片视图

  2. BoxFit.contain :根据图片的比例完全展示在视图上,不会被裁剪。

  3. BoxFit.cover: 根据图片的比例,填充这个视图,会被裁剪。

  4. BoxFit.fitWidth 根据图片的宽度自适应视图

  5. BoxFit.fitHeight 根据图片的高度,自适应视图

3.3 图片背景色

  1. color: 设置背景色
  2. colorBlendMode: 混合模式, 用BlendMode组件来实现

代码案例:

dart 复制代码
child: Image.network(
              'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F1129%2F27ab50dfj00snowf20035d200u000tug008t008r.jpg&thumbnail=660x2147483647&quality=80&type=jpg',
              scale: 2.0,
              fit: BoxFit.fitHeight,
              color: Colors.greenAccent,
              colorBlendMode: BlendMode.difference,
            )

3.4 repeat属性的使用

需要使用ImageRepeat组件来实现,常用的模式有:

  1. ImageRepeat.repeat
  2. ImageRepeat.repeatX
  3. ImageRepeat.repeatY

3.5 本地图片的使用

首先,在项目的根目录中,添加一个文件夹, 命名为images,然后把图片拖进去,如下图:

其次,项目的pubspec.yaml的文件中,配置本地图片,如下图:

最后,在代码中引用Image.asset('images/picture_1.png'),代码如下:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: "图片本地展示",
    home: FirstPage()
  ));
}

 class FirstPage extends StatelessWidget {
  const FirstPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("图片本地加载")),
      body: Center(
      	// 引用本地图片的代码
        child: Image.asset('images/picture_1.png'),
      ),
    );
  }
}

4. ListView 的初级使用

4.1 竖向列表的使用

代码案例1:

dart 复制代码
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 的demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Widget'),
        ),
        body: ListView(
          children: <Widget>[
            ListTile(
              leading: Icon(Icons.accessible_forward_outlined),
              title: Text('标题提标题'),
            ),
            ListTile(
              leading: Icon(Icons.accessibility_new_outlined),
              title: Text('标题提标题'),
            ),
            ListTile(
              leading: Icon(Icons.access_alarm),
              title: Text('标题提标题'),
            ),
          ],
        ),
      ),
    );
  }
}

代码案例2:

dart 复制代码
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 的demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView Widget'),
        ),
        body: ListView(
          children: <Widget>[
            Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg'),
            Image.network('https://img1.baidu.com/it/u=1368815763,3761060632&fm=253&fmt=auto&app=138&f=JPEG?w=760&h=434'),
            Image.network('https://i-blog.csdnimg.cn/blog_migrate/41635df939e6dd13c6d5e2af785d358b.jpeg'),
            Image.network('https://img2.baidu.com/it/u=2848534206,1976619941&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=896'),
          ],
        ),
      ),
    );
    
  }
}

效果图:

4.2 横向列表的使用

用scrollDirection这个属性来设置列表滚动的方向:

  1. Axis.horizontal 横向滚动
  2. Axis.vertical 纵向滚动

4.3 动态列表的使用

代码案例:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyApp(
      items: List<String>.generate(
        100,
        (i) => 'Heading $i')
    ),
  );
}


class MyApp extends StatelessWidget {

  final List<String> items;

  const MyApp({super.key, required this.items});

  @override
  Widget build(BuildContext context) {
    final itemList = items; // 如果items为null,则使用默认值
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Example App')),
        body: ListView.builder(
          itemCount: itemList.length,
          itemBuilder: (context, index) {
            return ListTile(title: Text(itemList[index]));
          },
        ),
      ),
    );
  }
}

5. 网络布局的使用

主要用GridView组件来实现,GridView提供了几种创建方式:

  1. GridView()
  2. GridView.builder()
  3. GridView.custom()
  4. GridView.count()

常用的属性有:

crossAxisCount: 3, 每一行展示几个item
mainAxisSpacing: 2.0, 上下的间距
crossAxisSpacing: 2.0, 左右的间距
childAspectRatio: 0.75 长和宽的比,用来设置每个子视图的大小

代码使用案例:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    FilmExample()
  );
}


class FilmExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "电影海报实例",
      home: Scaffold(
        appBar: AppBar(
          title: Text("电影海报实例"),
        ),
        body: GridViewDelegateTest(),
      )
    );
    
  }
}


// GridViewDelegate 的使用案例
class GridViewDelegateTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,  // 每一行展示几个item
        mainAxisSpacing: 2.0,  // 上下的间距
        crossAxisSpacing: 2.0, // 左右的间距
        childAspectRatio: 0.75 // 长宽比
      ),
      children: [
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img1.baidu.com/it/u=1368815763,3761060632&fm=253&fmt=auto&app=138&f=JPEG?w=760&h=434', fit: BoxFit.cover),
        Image.network('https://i-blog.csdnimg.cn/blog_migrate/41635df939e6dd13c6d5e2af785d358b.jpeg', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img1.baidu.com/it/u=1368815763,3761060632&fm=253&fmt=auto&app=138&f=JPEG?w=760&h=434', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img2.baidu.com/it/u=2848534206,1976619941&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=896', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img1.baidu.com/it/u=1368815763,3761060632&fm=253&fmt=auto&app=138&f=JPEG?w=760&h=43', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img2.baidu.com/it/u=2848534206,1976619941&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=896', fit: BoxFit.cover),
        Image.network('https://i-blog.csdnimg.cn/blog_migrate/41635df939e6dd13c6d5e2af785d358b.jpeg', fit: BoxFit.cover),
        Image.network('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg', fit: BoxFit.cover),
        Image.network('https://img2.baidu.com/it/u=2848534206,1976619941&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=896', fit: BoxFit.cover),
        Image.network('https://i-blog.csdnimg.cn/blog_migrate/41635df939e6dd13c6d5e2af785d358b.jpeg', fit: BoxFit.cover),
      ],
    );
  }
}

效果图:

6. 水平方向的布局案例

水平方向布局的设置,用Row的组件来设置,其中有个小知识点:Expanded组件,是填充组件:

如果设置了3个Expanded,表示将三个视图将屏幕的宽度3等份平铺。

如果三个视图中,中间的视图用Expanded包裹着,那第一个和第三个视图按照自身的大小展示,第二个视图填充剩余的宽度。

代码案例:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyExampleApp()
  );
}

class MyExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "布局RowWidge",
      home: Scaffold(
        appBar: AppBar(
          title: Text("布局RowWidge案例"),
        ),
        body: Row(
          children: [
            Expanded(
              child: ElevatedButton(
              onPressed: (){},
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.redAccent, // foreground (text) color
              ),
              child: Text("红色按钮")
            )
            ),
            Expanded(child: ElevatedButton(
              onPressed: (){},
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.orangeAccent, // foreground (text) color
              ),
              child: Text("橙色按钮")
            )),
            Expanded(child: ElevatedButton(
              onPressed: (){},
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.blueAccent, // foreground (text) color
              ),
              child: Text("蓝色按钮")
            )),
          ],
        ),
      ),
    );
  }
}

7. 垂直方向的布局案例

用Column组件来实现垂直方向的布局,代码案例:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyExampleApp()
  );
}

// ---布局ColumnWidge的案例---
class MyExampleApp extends StatelessWidget {
   @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "垂直方向布局案例",
      home: Scaffold(
        appBar: AppBar(
          title: Text("垂直方向布局案例"),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,  // 主轴对齐方式:垂直的
          crossAxisAlignment: CrossAxisAlignment.center,  // 副轴对齐方式:左右的
          children: [
            Text('111111'),
            Expanded(child: Text('222222')),
            Text('333333333333')
          ],
        ),
      ),
    );
  }
}

8. 层叠布局案例

8.1 只有两个视图的stack的使用方法

用Stack组件来实现,最少需要两个子视图,其中有个属性alignment是子控件内部按照什么对齐方式对齐:

最小是0,最大是1, 是相对于stack内部空间中,最大视图的位置来说的

代码案例:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyExampleApp()
  );
}

class MyExampleApp extends StatelessWidget {
 @override
  Widget build(BuildContext context) {

     var stack = Stack(
      // 内部控件的对齐方式,最小是0,最大是1, 是相对于stack内部空间中,最大视图的位置来说的
      alignment: FractionalOffset(0.5, 0.8),  
      children: [
        CircleAvatar(
          backgroundImage: NetworkImage('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg'),
          radius: 100.0,
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.blueAccent
          ),
          padding: EdgeInsets.all(5.0),
          child: Text('ZhuZhu'),
        )
      ],
    );

    return MaterialApp(
      title: "布局案例",
      home: Scaffold(
        appBar: AppBar(
          title: Text("层叠布局"),
        ),
        body: Center(
          child: stack,
        ),
      ),
    );
  }
}

效果图:

8.2 如果stack的子视图多于2个的使用方法

如果stack子视图大于2个,那么用alignment 的对齐方式来布局,就非常的不优化,此时,可以选择Positioned组件来设置布局,代码如下:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyExampleApp()
  );
}

class MyExampleApp extends StatelessWidget {
 @override
  Widget build(BuildContext context) {

     var stack = Stack(
      // 内部控件的对齐方式,最小是0,最大是1, 是相对于stack内部空间中,最大视图的位置来说的
      alignment: FractionalOffset(0.5, 0.8),  
      children: [
        CircleAvatar(
          backgroundImage: NetworkImage('https://pic.rmb.bdstatic.com/bjh/news/0fc6b71c59a69f39cf2e1244d10eaedc.jpeg'),
          radius: 100.0,
        ),
        Positioned(
          top: 10.0,
          left: 10.0,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.blueAccent
            ),
            padding: EdgeInsets.all(5.0),
            child: Text("zhuzhu"),
          )
        ),
        Positioned(
          bottom: 10.0,
          right: 10.0,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.deepOrange
            ),
            padding: EdgeInsets.all(5.0),
            child: Text("技术猪"),
          )
        ),
      ],
    );

    return MaterialApp(
      title: "布局案例",
      home: Scaffold(
        appBar: AppBar(
          title: Text("层叠布局"),
        ),
        body: Center(
          child: stack,
        ),
      ),
    );
  }
}

效果图如下:

8. 卡片布局案例

用Card组件来实现,代码如下:

dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(
    MyExampleApp()
  );
}

class MyExampleApp extends StatelessWidget {
 @override
  Widget build(BuildContext context) {

     var card = Card(
      child: Column(
        children: [
          ListTile(
            title: Text("福建省厦门市湖里区", style: TextStyle(fontWeight: FontWeight.w700)),
            subtitle: Text("zhuzhu:15100001234"),
            leading: Icon(Icons.account_box, color: Colors.blueAccent),
          ),
          Divider(),
          ListTile(
            title: Text("北京市海淀区中关村", style: TextStyle(fontWeight: FontWeight.w700)),
            subtitle: Text("guoguo:15100001234"),
            leading: Icon(Icons.account_box, color: Colors.blueAccent),
          ),
          Divider(),
          ListTile(
            title: Text("上海市浦江区", style: TextStyle(fontWeight: FontWeight.w700)),
            subtitle: Text("xuexue:15100001234"),
            leading: Icon(Icons.account_box, color: Colors.blueAccent),
          ),
        ],
      ),
     );

    return MaterialApp(
      title: "布局案例",
      home: Scaffold(
        appBar: AppBar(
          title: Text("层叠布局"),
        ),
        body: Center(
          child: card,
        ),
      ),
    );
  }

效果图:

相关推荐
SoaringHeart16 小时前
Flutter最佳实践:用 flutter_html 渲染富文本
前端·flutter
恋猫de小郭1 天前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
程序员老刘2 天前
跨平台开发地图 | 2026年11月
flutter·ai编程·客户端
传奇开心果编程2 天前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
恋猫de小郭2 天前
Flutter Native Interop 稳定了,Platform Channel 要退场了
android·前端·flutter
好的佩奇3 天前
Dart 之可迭代对象与生成器
android·flutter·dart
恋猫de小郭3 天前
Flutter Analyzer 系列坑推进,必看,AI 时代这玩意最吃你内存
android·前端·flutter
LinXunFeng4 天前
拿竞品 App 一扫,技术栈全暴露了
android·flutter·开源
传奇开心果编程4 天前
【Flutter踩坑排雷】第28课:平台目录缺失与修复坑|`flutter create` 的“重建”与“覆盖”边界
android·flutter·ios·移动开发·跨平台·dart·声明式ui
程序员老刘·5 天前
Flutter 3.50更新,开发者应该关注什么?
flutter·ai编程·跨平台开发