Flutter系列文章-Flutter UI进阶

在本篇文章中,我们将深入学习 Flutter UI 的进阶技巧,涵盖了布局原理、动画实现、自定义绘图和效果、以及 Material 和 Cupertino 组件库的使用。通过实例演示,你将更加了解如何创建复杂、令人印象深刻的用户界面。

第一部分:深入理解布局原理

1. 灵活运用 Row 和 Column

Row 和 Column 是常用的布局组件,但灵活地使用它们可以带来不同的布局效果。例如,使用 mainAxisAlignment 和 crossAxisAlignment 可以控制子组件在主轴和交叉轴上的对齐方式。

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Container(width: 50, height: 50, color: Colors.red),
    Container(width: 50, height: 50, color: Colors.green),
    Container(width: 50, height: 50, color: Colors.blue),
  ],
)

2. 弹性布局 Flex 和 Expanded

Flex 和 Expanded 可以用于实现弹性布局,让组件占据可用空间的比例。例如,下面的代码将一个蓝色容器占据两倍宽度的空间。

Row(
  children: [
    Container(width: 50, height: 50, color: Colors.red),
    Expanded(
      flex: 2,
      child: Container(height: 50, color: Colors.blue),
    ),
  ],
)

第二部分:动画和动效实现

1. 使用 AnimatedContainer

AnimatedContainer 可以实现在属性变化时自动产生过渡动画效果。例如,以下代码在点击时改变容器的宽度和颜色。

class AnimatedContainerExample extends StatefulWidget {
  @override
  _AnimatedContainerExampleState createState() => _AnimatedContainerExampleState();
}

class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
  double _width = 100;
  Color _color = Colors.blue;

  void _animateContainer() {
    setState(() {
      _width = _width == 100 ? 200 : 100;
      _color = _color == Colors.blue ? Colors.red : Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _animateContainer,
      child: AnimatedContainer(
        width: _width,
        height: 100,
        color: _color,
        duration: Duration(seconds: 1),
        curve: Curves.easeInOut,
      ),
    );
  }
}

2. 使用 Hero 动画

Hero 动画可以在页面切换时产生平滑的过渡效果。在不同页面中使用相同的 tag,可以让两个页面之间的共享元素过渡更加自然。

class PageA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => PageB(),
        ));
      },
      child: Hero(
        tag: 'avatar',
        child: CircleAvatar(
          radius: 50,
          backgroundImage: AssetImage('assets/avatar.jpg'),
        ),
      ),
    );
  }
}

class PageB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Hero(
          tag: 'avatar',
          child: CircleAvatar(
            radius: 150,
            backgroundImage: AssetImage('assets/avatar.jpg'),
          ),
        ),
      ),
    );
  }
}

第三部分:自定义绘图和效果

1. 使用 CustomPaint 绘制图形

CustomPaint 允许你自定义绘制各种图形和效果。以下是一个简单的例子,绘制一个带边框的矩形。

class CustomPaintExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: RectanglePainter(),
      child: Container(),
    );
  }
}

class RectanglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2;

    canvas.drawRect(Rect.fromLTWH(50, 50, 200, 100), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}

第四部分:Material 和 Cupertino 组件库

1. 使用 Material 组件

Material 组件库提供了一系列符合 Material Design 规范的 UI 组件。例如,AppBar、Button、Card 等。以下是一个使用 Card 的例子。

Card(
  elevation: 4,
  child: ListTile(
    leading: Icon(Icons.account_circle),
    title: Text('John Doe'),
    subtitle: Text('Software Engineer'),
    trailing: Icon(Icons.more_vert),
  ),
)

2. 使用 Cupertino 组件

Cupertino 组件库提供了 iOS 风格的 UI 组件,适用于 Flutter 应用在 iOS 平台上的开发。例如,CupertinoNavigationBar、CupertinoButton 等。

dart
Copy code
CupertinoNavigationBar(
middle: Text(‘Cupertino Example’),
trailing: CupertinoButton(
child: Text(‘Done’),
onPressed: () {},
),
)

第五部分:综合实例

以下是一个更加综合的例子,涵盖了之前提到的布局、动画、自定义绘图和 Material/Cupertino 组件库的知识点。

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ExampleScreen(),
    );
  }
}

class ExampleScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Advanced UI Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedRotateExample(),
            SizedBox(height: 20),
            CustomPaintExample(),
            SizedBox(height: 20),
            PlatformWidgetsExample(),
          ],
        ),
      ),
    );
  }
}

class AnimatedRotateExample extends StatefulWidget {
  @override
  _AnimatedRotateExampleState createState() => _AnimatedRotateExampleState();
}

class _AnimatedRotateExampleState extends State<AnimatedRotateExample> {
  double _rotation = 0;

  void _startRotation() {
    Future.delayed(Duration(seconds: 1), () {
      setState(() {
        _rotation = 45;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        GestureDetector(
          onTap: () {
            _startRotation();
          },
          child: AnimatedBuilder(
            animation: Tween<double>(begin: 0, end: _rotation).animate(
              CurvedAnimation(
                parent: ModalRoute.of(context)!.animation!,
                curve: Curves.easeInOut,
              ),
            ),
            builder: (context, child) {
              return Transform.rotate(
                angle: _rotation * 3.1416 / 180,
                child: child,
              );
            },
            child: Container(
              width: 100,
              height: 100,
              color: Colors.blue,
              child: Icon(
                Icons.star,
                color: Colors.white,
              ),
            ),
          ),
        ),
        Text('Tap to rotate'),
      ],
    );
  }
}

class CustomPaintExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: CirclePainter(),
      child: Container(
        width: 200,
        height: 200,
        alignment: Alignment.center,
        child: Text(
          'Custom Paint',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
    );
  }
}

class CirclePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;
    final paint = Paint()
      ..color = Colors.orange
      ..style = PaintingStyle.fill;

    canvas.drawCircle(center, radius, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

class PlatformWidgetsExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Material(
          elevation: 4,
          child: ListTile(
            leading: Icon(Icons.account_circle),
            title: Text('John Doe'),
            subtitle: Text('Software Engineer'),
            trailing: Icon(Icons.more_vert),
          ),
        ),
        SizedBox(height: 20),
        CupertinoButton.filled(
          child: Text('Explore'),
          onPressed: () {},
        ),
      ],
    );
  }
}

这个示例演示了一个综合性的界面,包括点击旋转动画、自定义绘图和 Material/Cupertino 组件。你可以在此基础上进一步扩展和修改,以满足更复杂的 UI 设计需求。

总结

在本篇文章中,我们深入学习了 Flutter UI 的进阶技巧。我们了解了布局原理、动画实现、自定义绘图和效果,以及 Material 和 Cupertino 组件库的使用。通过实例演示,你将能够更加自信地构建复杂、令人印象深刻的用户界面。

希望这篇文章能够帮助你在 Flutter UI 进阶方面取得更大的进展。如果你有任何问题或需要进一步的指导,请随时向我询问。祝你在 Flutter 开发的道路上取得成功!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/69837.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Monge矩阵

Monge矩阵 对一个m*n的实数矩阵A&#xff0c;如果对所有i&#xff0c;j&#xff0c;k和l&#xff0c;1≤ i<k ≤ m和1≤ j<l ≤ n&#xff0c;有 A[i,j]A[k,l] ≤ A[i,l]A[k,j] 那么&#xff0c;此矩阵A为Monge矩阵。 换句话说&#xff0c;每当我们从矩阵中挑…

腾讯云服务器镜像操作系统大全_Linux_Windows清单

腾讯云CVM服务器的公共镜像是由腾讯云官方提供的镜像&#xff0c;公共镜像包含基础操作系统和腾讯云提供的初始化组件&#xff0c;公共镜像分为Windows和Linux两大类操作系统&#xff0c;如TencentOS Server、Windows Server、OpenCloudOS、CentOS Stream、CentOS、Ubuntu、Deb…

【C++精华铺】6.C++类和对象(下)类与对象的知识补充及编译器优化

目录 1. 再谈构造 1.1 成员变量的初始化&#xff08;初始化列表&#xff09; 1.2 初始化列表的行为 1.3 explicit关键字 2. 类中的static成员 2.1 静态成员变量 2.2 静态成员函数 3. 友元 3.1 友元函数 3.1 友元类 4. 内部类 5. 匿名对象 6. 对象拷贝时候的编译器优化…

设计模式之策略模式

目录 背景步骤关于策略模式&#xff0c;他的业务需求是什么样的场景&#xff1f;什么是策略模式&#xff1f;当然策略模式的实现不仅仅是策略模式&#xff0c;他和简单工厂的设计模式有什么样的关系&#xff1f;方法是什么 总结 背景 问题是最好的老师 关于策略模式&#xff0…

springboot文件上传和下载接口的简单思路

springboot文件上传和下载的简单思路 文件上传文件下载 文件上传 在springboot中&#xff0c;上传文件只需要在接口中通过 MultipartFile 对象来获取前端传递的数据&#xff0c;然后将数据存储&#xff0c;并且返回一个对外访问路径即可。一般对于上传文件的文件名&#xff0c…

在 Android 上使用机器学习套件检测人脸

须知事项 此 API 需要 Android API 级别 19 或更高级别。确保应用的 build 文件使用的 minSdkVersion 值不小于 19。 请务必在您的项目级 build.gradle 文件中的 buildscript 和 allprojects 部分添加 Google 的 Maven 代码库。 将 Android 版机器学习套件库的依赖项添加到模…

【MATLAB第68期】基于MATLAB的LSTM长短期记忆网络多变量时间序列数据多步预测含预测未来(非单步预测)

【MATLAB第68期】基于MATLAB的LSTM长短期记忆网络多变量时间序列数据多步预测含预测未来&#xff08;非单步预测&#xff09; 输入前25个时间&#xff0c;输出后5个时间 一、数据转换 1、原始数据 5列时间序列数据&#xff0c;70行样本 705 数据矩阵结构 2、数据转换 将…

【论文阅读】NoDoze:使用自动来源分类对抗威胁警报疲劳(NDSS-2019)

NODOZE: Combatting Threat Alert Fatigue with Automated Provenance Triage 伊利诺伊大学芝加哥分校 Hassan W U, Guo S, Li D, et al. Nodoze: Combatting threat alert fatigue with automated provenance triage[C]//network and distributed systems security symposium.…

2023/8/11题解

时间限制: 1000MS 内存限制: 65536KB 解题思路 建树 模拟 &#xff0c;复杂在于建树&#xff0c;此处从题目需求可知需要按层建树&#xff0c;所以需要队列模拟&#xff0c;查找比较容易就是普通的深搜 参考代码 #include<bits/stdc.h> using namespace std; vector<…

Windows 环境下 Python3 离线安装 cryptography 失败

发布Flask Web项目时&#xff0c;报错缺少Cryptography&#xff0c;于是尝试重新安装该库&#xff0c;但本机没有网络&#xff0c;只支持手动离线安装&#xff0c;尝试了pip、setup.py两种方式安装&#xff0c;结果都报错。。最后使用将安装包拷贝至本机(在其他电脑上安装的sit…

【算法挨揍日记】day01——双指针算法_移动零、 复写零

283.移动零 283. 移动零https://leetcode.cn/problems/move-zeroes/ 题目&#xff1a; 给定一个数组 nums&#xff0c;编写一个函数将所有 0 移动到数组的末尾&#xff0c;同时保持非零元素的相对顺序。 请注意 &#xff0c;必须在不复制数组的情况下原地对数组进行操作。 …

gitee分支合并

合并dev分支到master&#xff08;合并到主分支&#xff09; git checkout master git merge dev //这里的dev表示你的分支名称 git push //推送到远程仓库 效果如下图 不报错就表示推送成功了&#xff0c;希望能帮助各位小伙伴

DevOps最佳实践和工具在本地环境中的概述

引言 最近&#xff0c;我进行了一次网上搜索&#xff0c;以寻找DevOps的概述&#xff0c;尽管有大量的DevOps工具和实践&#xff0c;但我无法找到一个综合的概述。因此&#xff0c;我开始了对DevOps生态系统和最佳实践的梳理&#xff0c;以创建一个整体视图,方便后续研究实践 C…

5.1 web浏览安全

数据参考&#xff1a;CISP官方 目录 Web应用基础浏览器所面临的安全威胁养成良好的Web浏览安全意识如何安全使用浏览器 一、Web应用基础 1、Web应用的基本概念 Web ( World wide Web) 也称为万维网 脱离单机Web应用在互联网上占据了及其重要的地位Web应用的发展&#xf…

K8s环境下监控告警平台搭建及配置

Promethues是可以单机搭建的&#xff0c;参考prometheus入门[1] 本文是就PromethuesGrafana在K8s环境下的搭建及配置 Prometheus度量指标监控平台简介 启动minikube minikube start 安装helm 使用Helm Chart 安装 Prometheus Operator: helm install prometheus-operator stabl…

AI:01-基于机器学习的深度学习的玫瑰花种类的识别

文章目录 一、数据集介绍二、数据预处理三、模型构建四、模型训练五、模型评估六、模型训练七、模型评估八、总结深度学习技术在图像识别领域有着广泛的应用,其中一种应用就是玫瑰花种类的识别。在本文中,我们将介绍如何使用机器学习和深度学习技术来实现玫瑰花种类的识别,并…

备忘录模式(C++)

定义 在不破坏封装性的前提下&#xff0c;捕获一-个对象的内部状态&#xff0c;并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。 应用场景 ➢在软件构建过程中&#xff0c;某些对象的状态在转换过程中&#xff0c;可能由于某种需要&#xff0c;要…

c++遍历当前windows目录

前言 设置vs的高级属性为使用多字节字符集&#xff0c;不然会报char类型的实参与LPCWSTR类型的形参类型不兼容的错误 代码 #include <iostream> #include <cstring> #include <windows.h>void listFiles(const char* dir);int main() {using namespace st…

【服务平台】Rancher运行和管理Docker和Kubernetes,提供管理生产中的容器所需的整个软件堆栈

Rancher是一个开源软件平台&#xff0c;使组织能够在生产中运行和管理Docker和Kubernetes。使用Rancher&#xff0c;组织不再需要使用一套独特的开源技术从头开始构建容器服务平台。Rancher提供了管理生产中的容器所需的整个软件堆栈。  完整软件堆栈 Rancher是供采用容器的团…

SpringBoot案例-部门管理-删除

目录 查看页面原型&#xff0c;明确需求 页面原型 需求 阅读接口文档 思路分析 功能接口开发 控制层&#xff08;Controllre类&#xff09; 业务层&#xff08;Service类&#xff09; 持久层&#xff08;Mapper类&#xff09; 接口测试 前后端联调 查看页面原型&a…
最新文章