【自学Flutter】33 自定义Widget 的使用(组合)
发布日期:2021-05-12 19:48:56 浏览次数:20 分类:精选文章

本文共 3198 字,大约阅读时间需要 10 分钟。

自定义Widget 的使用(组合)

源代码

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State
{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CustomSquare(
height: 50.0,
width: 50.0,
color: Colors.blueAccent,
child: Text("你点击了带提示的自定义方形"),
),
CustomSquare(
height: 50.0,
width: 150.0,
color: Colors.blueAccent,
child: Text("你点击了带提示的自定义方形"),
),
CustomSquare(
height: 100.0,
width: 50.0,
color: Colors.blueAccent,
child: Text("你点击了带提示的自定义方形"),
),
CustomSquare(
height: 100.0,
width: 50.0,
color: Colors.blueAccent,
child: Text("你点击了带提示的自定义方形"),
),
],
),
),
),
);
}
}
// 制作带提示的自定义大小高宽度的方形
class CustomSquare extends StatelessWidget {
final Color color;
final double width;
final double height;
final Text child;
CustomSquare({
this.color,
this.width,
this.height,
@required this.child,
});
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
color: color,
child: Builder(builder: (context) {
return InkWell(
onTap: () {
Scaffold.of(context).showSnackBar(SnackBar(content: child));
},
);
}),
);
}
}

解释源代码

上述代码展示了如何在Flutter中使用自定义Widget进行组合开发。整个代码分为两部分:MyApp widget和自定义的CustomSquare widget。

MyApp widget是应用程序的主 widget,负责布局和显示内容。在构建 widget tree 时,返回了一个 Scaffold widget,作为应用程序的主页面。此外,页面的中央区域包含一个竖直方向的 Column widget,用于布局多个 CustomSquare widget。

每个 CustomSquare widget都是一个高度可定制的窗口 widget。开发者可以根据需求指定高度、宽度和颜色等属性。内部集成了 InkWell widget,用于检测点击时间,并在点击时展示一个 SnackBar widget,显示点击后的提示信息。

这个实现通过组合自定义 widget 和系统 widget,结合 Material Design 的美化效果,实现了一个响应式且用户友好的界面。这种组合开发方式能够显著提高开发效率,确保代码的可维护性和扩展性。

效果展示

通过代码运行可观察到以下效果:

  • 应用程序展示一个蓝色方框,方框内部包含带有点击提示的文本内容。
  • 它们以不同尺寸和相同的样式排列在页面中央位置。
  • 点击任意一个方框后,方框会以轻微效果震动,并在其上方显示一个带有点击提示的SnackBar。
  • 这种设计方便用户快速理解 widget 的功能及其使用方法,同时提供了良好的用户交互体验。

    如需进一步修改或扩展应用功能,可以分别对 CustomSquare widget 的颜色、大小和子 widget 进行定制,以满足不同的开发需求。

    上一篇:【自学Flutter】34 自定义Widget(自绘)
    下一篇:【自学Flutter】32 交错动画的使用

    发表评论

    最新留言

    逛到本站,mark一下
    [***.202.152.39]2025年04月18日 05时19分47秒