flutter - 我需要做什么才能使用我的按钮小部件链接到另一个文件?
问题描述
我还在学习编码。如何将所有按钮小部件存储在另一个文件中并将其导入到我的主文件中?这是代码:
class _testState extends State<test> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[900],
appBar: AppBar(
title: Text('test'),
backgroundColor: Colors.red[900],
),
body: GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
children: [
//buttons
],
),
);
}
}
如何获取下面的代码并将其放入另一个文件中,然后通过按钮注释将其链接到上面的文件?
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 9.0, 0.0, 0.0),
child: TextButton.icon(
onPressed: () => {},
icon: Column(
children: [
Icon(
Icons.add,
color: Colors.white,
size: 75,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'Label',
style: TextStyle(
color: Colors.white,
),
),
),
],
),
label: Text(
'', //'Label',
style: TextStyle(
color: Colors.white,
),
),
),
),
解决方案
-首先,创建一个新文件,将其命名为jeff.dart
.
-其次,在新文件中键入:stless
. 回车,Flutter 会自动StatelessWidget
为你新建一个。将类名更改为JeffButton
. 现在,它看起来像这样:
class JeffButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
);
}
}
- 复制粘贴按钮的代码,替换
Container()
掉.Congratulations!你有杰夫巴顿!现在您可以在任何地方使用它:
类 JeffButton 扩展 StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 9.0, 0.0, 0.0),
child: TextButton.icon(
onPressed: () => {},
icon: Column(
children: [
Icon(
Icons.add,
color: Colors.white,
size: 75,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'Label',
style: TextStyle(
color: Colors.white,
),
),
),
],
),
label: Text(
'', //'Label',
style: TextStyle(
color: Colors.white,
),
),
),
);
}
}
现在只需将它添加到您需要它的地方;):
children: [
//buttons
JeffButton(),
],
请记住将 jeff.dart 文件导入到您使用它的位置,您可以通过移动光标以JeffButton(),
显示快速修复,选择Import: ....
(这是第一个选项)轻松完成。如果您不知道,这是如何显示快速修复:https ://flutter.dev/docs/development/tools/flutter-fix
推荐阅读
- java - 升级到 Gradle 5.2.1 不会生成 *-all.jar
- mongodb - Mongo - 重复文档的 ObjectId 是否不同?
- python - 如何防止将字符串分解为字符列表?
- excel - VBA 擅长。与 Internet Explorer 网页的源交互
- c# - 如何在不使用 asp:BoundFields 的情况下选择网格视图中的行
- amazon-s3 - AWS Glue - 如何配置 Crawler 以创建包含 S3 文件名的表
- javascript - ReactJS:更改组件属性后重新渲染不起作用
- c# - 删除/替换流阅读器字符串中的多个单词
- sql-server - 如何使用 CTE 进行插入
- python - 如何在 QGraphicsView 中自动正确设置 rect?