大多数时候,您可能会发现自己使用某种预定义格式填充 ListView。您可以使用 Flutter 中称为ListTile小部件的现成小部件来提供帮助,而不是自己使用行、列和容器创建此布局。
在本教程中,我将通过一些实际示例向您展示如何在 Flutter 应用程序中添加 ListTile 小部件。
以下是我们今天要介绍的内容:
什么是 ListTile?
ListTile 变体
管理 ListTile 主题
添加分隔符
添加滑动关闭行为
更改 ListTile 高度
定制
Flutter 中的 ListTile 小部件是一个显示相关信息的 UI 元素。
它遵循 Material Design 的List规范。一个典型的 ListTile 分为三个部分;开始、中心和结束。开始部分包含领先的小部件;中心部分包括标题和副标题;End 部分包含尾随小部件。
主要用于填充ListView、Column、Row等可滚动视图。例如,您可以使用 ListTile 显示待办事项、电子邮件、导航选项等的列表。您还可以通过点击 ListTile 来接收点击事件。
如果您是视觉学习者,请查看此快速视频教程:
这是在 ListView 小部件中显示 ListTile 的最少代码:
ListView(
children: const [
ListTile(
leading: Icon(Icons.car_rental),
title: Text('Car'),
trailing: Icon(Icons.more_vert),
),
ListTile(
leading: Icon(Icons.flight),
title: Text('Flight'),
trailing: Icon(Icons.more_vert),
),
ListTile(
leading: Icon(Icons.train),
title: Text('Train'),
trailing: Icon(Icons.more_vert),
)
],
)
以下是将代码转换为设计的方式:
当您想使用 ListTile 填充可能来自后端的长列表时,您可以将单个 ListTile 小部件包装在 ListView.Builder 中,并在 ListTile 中显示数据,如以下代码所示:
final List<String> items = List<String>.generate(10000, (i) => '$i');
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundColor: const Color(0xff764abc),
child: Text(items[index]),
),
title: Text('Item ${items[index]}'),
subtitle: Text('Item description'),
trailing: Icon(Icons.more_vert),
);
},
)
输出:
还有其他类型的 ListTile 允许您对其执行特定操作。
这些是:
CheckboxListTile
RadioListTile
SwitchListTile
CheckboxListTile小部件是 ListTile 和Checkbox小部件的组合。
您可以使用此小部件将任何项目标记为已完成——例如;待办事项。默认情况下,复选框显示在 ListTile 的右侧(对于从左到右的语言)。
以下是添加 CheckboxListTile 小部件的方法:
class Language {
String name;
bool isChecked;
Language(this.name, {this.isChecked = false});
}
// 1.
final List<Language> languages = [Language('English'), Language('French'), Language('German')];
ListView.builder(
itemCount: languages.length,
itemBuilder: (context, index) {
return CheckboxListTile(
// 2.
title: Text('${languages[index].name}'),
// 3.
value: languages[index].isChecked,
// 4.
onChanged: (bool? value) {
setState(() {
languages[index].isChecked = value!;
});
},
// 5.
secondary: const Icon(Icons.language),
);
},
)
代码块中的数字解释:
包含语言列表的变量
这显示了复选框标签
这决定了是否选中或取消选中该项目
当您点击 ListTile 时会调用它
这是一个领先的图标
输出:
要交换辅助(前导)小部件和复选框,您可以使用该controlAffinity属性并将其设置为ListTileControlAffinity.leading.
您还可以通过添加checkboxShape参数并将其设置为 来更改复选框的形状RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))。
RadioListTile小部件是ListTile和RadioButton小部件的组合——该小部件用于从项目列表中选择单个选项。
以下是添加 RadioListTile 小部件的方法:
// 1.
enum Gender { male, female }
// 2.
Gender? _gender = Gender.male;
ListView(
children: [
// 3.
RadioListTile<Gender>(
secondary: Icon(Icons.male),
controlAffinity: ListTileControlAffinity.trailing,
title: const Text('Male'),
// 4.
value: Gender.male,
// 5.
groupValue: _gender,
// 6.
onChanged: (Gender? value) {
setState(() {
_gender = value;
});
},
),
RadioListTile<Gender>(
secondary: Icon(Icons.female),
controlAffinity: ListTileControlAffinity.trailing,
title: const Text('Female'),
value: Gender.female,
groupValue: _gender,
onChanged: (Gender? value) {
setState(() {
_gender = value;
});
},
),
],
)
代码块中的数字解释:
包含RadioListTile的所有选择值的枚举
这使用枚举保存默认选择
添加枚举类型的 RadioListTile
将选择值分配给当前列表图块。ListTile 代表这个值
这用于显示当前选择的值
当您切换单选按钮时,它会通过选择调用
输出:
SwitchListTile小部件是 ListTile 和Switch小部件的组合。
您可以使用此小部件构建允许用户打开或关闭应用程序设置的 UI 交互。
以下是添加 SwitchListTile 小部件的方法:
class Appliance {
String name;
bool isOn;
Appliance(this.name, {this.isOn = false});
}
// 1.
final List<Appliance> appliances = [
Appliance('TV'),
Appliance('Fan'),
Appliance('Refrigerator'),
];
ListView.builder(
itemCount: appliances.length,
itemBuilder: (context, index) {
return SwitchListTile(
// 2.
title: Text('${appliances[index].name}'),
// 3.
value: appliances[index].isOn,
// 4.
onChanged: (bool value) {
setState(() {
appliances[index].isOn = value;
});
},
);
},
)
代码块中的数字解释:
包含设备列表的变量
这显示了 ListTile 的名称或标题
这决定了是打开还是关闭开关
这在您切换开关时调用
输出:
主题是开发前端应用程序的重要方面。主题传达了您的品牌,如果管理不当,您可能会浪费大量时间让所有 UI 元素都遵循相同的规则。
假设您想要更改 ListTile 的外观以匹配您的设计。你真的有以下两个选择:
在小部件级别更改主题
在应用程序级别更改主题
您可以通过直接修改其属性(例如颜色、形状和大小)来更改 ListTile 的外观。
以下是更改 ListTile 的背景颜色、文本颜色和图标颜色的方法:
return ListTile( // 1. tileColor: Colors.redAccent, // 2. textColor: Colors.white, // 3. iconColor: Colors.white, );
代码块中的数字解释:
这会改变 ListTile 的背景颜色
这会更改 ListTile 上显示的所有文本的颜色
这会更改出现在 ListTile 上的所有图标的颜色
您可能希望在所有应用页面中更改 ListTile 小部件的视觉美感。您可以通过定义listTileTheme然后添加ListTileThemeData小部件来做到这一点。
超过 20 万开发人员使用 LogRocket 来创造更好的数字体验了解更多 →
在ListTileThemeData小部件内部,您可以为项目中的所有 ListTile 小部件指定要更改的所有属性。
这是代码示例:
return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, listTileTheme: ListTileThemeData( tileColor: Colors.redAccent, textColor: Colors.white, iconColor: Colors.white, ), ), home: MyHomePage(), );
第一种和第二种方法都产生与以下相同的结果:
添加分隔线可以帮助您清楚地区分项目,尤其是当项目在中心部分以三行显示时。
要在 ListTile 项目之间添加分隔线,请添加ListView小部件。在里面ListView,添加ListTile.divideTiles带有 tiles 属性和 ListTiles 列表。
代码示例:
ListView(
children: ListTile.divideTiles(context: context, tiles: [
ListTile(
leading: Icon(Icons.car_rental),
title: Text('Car'),
),
ListTile(
leading: Icon(Icons.flight),
title: Text('Flight'),
),
ListTile(
leading: Icon(Icons.train),
title: Text('Train'),
),
]).toList(),
)
输出:
如果您使用ListView.Builder,则可以将其替换为ListView.separated并添加separatorBuilder返回分隔符的参数。
代码示例:
ListView.separated( // <-- SEE HERE
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundColor: const Color(0xff764abc),
child: Text(items[index]),
),
title: Text('Item ${items[index]}'),
subtitle: Text('Item description'),
trailing: Icon(Icons.more_vert),
);
},
separatorBuilder: (context, index) { // <-- SEE HERE
return Divider();
},
)
输出:
滑动关闭功能允许您使用滑动手势从列表中删除特定的 ListTile。例如,您可以使用此功能从列表中删除一封电子邮件。
以下是步骤:
将您的ListTile小部件包装在Dismissible小部件中
在 Dismissible 小部件中,添加onDismissed参数并注册回调。在这里,您可以编写从列表中删除项目的逻辑。
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Dismissible( // Step 1
key: Key(items[index]),
onDismissed: (direction) { // Step 2
setState(() {
items.removeAt(index);
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${items[index]} dismissed')));
},
child: ListTile(
//visualDensity: VisualDensity(vertical: 4),
leading: CircleAvatar(
backgroundColor: const Color(0xff764abc),
child: Text(items[index]),
),
title: Text('Item ${items[index]}'),
subtitle: Text('Item description'),
trailing: Icon(Icons.more_vert),
),
);
},
)
)
(注意:以上代码仅从 UI 中删除 ListTile,您必须自己编写业务逻辑才能从数据库中删除该项目)
输出:
有时您可能想在一定程度上调整 ListTile 的高度。ListTile 小部件不直接支持 height 属性,因为它的尺寸根据材料设计规范受到限制。畅听FM电台App,免登录免费畅听所有电台节目,无限制使用多地区FM频道!因此,为了增加或减少 ListTile 的高度,您可以使用该visualDensity属性。
将 设置visualDensity为正数将增加 ListTile 高度,而负数将降低高度。
(注意:您可以设置的最大值和最小值是4和-4)
这是代码示例:
ListTile(
visualDensity: VisualDensity(vertical: 4), //<-- SEE HERE
leading: CircleAvatar(
backgroundColor: const Color(0xff764abc),
child: Text(items[index]),
),
title: Text('Item ${items[index]}'),
subtitle: Text('Item description'),
trailing: Icon(Icons.more_vert),
);
输出:
您可以利用可用属性向 ListTile 添加各种自定义项。例如,您可以更改它的颜色(在不同的状态,如悬停、按下等)、形状、在标题和其他元素之间添加空间,以及更改它的高度等。
不要错过来自 LogRocket 的精选时事通讯The Replay
了解LogRocket 的 Galileo 如何消除噪音以主动解决应用程序中的问题
使用 React 的 useEffect优化应用程序的性能
在多个 Node 版本之间切换
了解如何使用 AnimXYZ 为您的 React 应用程序制作动画
探索 Tauri,一个用于构建二进制文件的新框架
比较NestJS 与 Express.js
您可以通过导航到其定义来查看它支持的所有属性。要查看所有属性,只需右键单击,然后转到> Delcation或Usages。
添加 ListTile 小部件可帮助您提高应用程序开发速度。它遵循材料规范,涵盖了有意义地展示项目所需的一切。
在本教程中,我们首先了解了如何添加 ListTile、它的类型以及如何管理主题,并涵盖了一些场景,例如添加分隔线和滑动关闭功能以及更改 ListTile 高度,所有这些都是我希望您在建立下一个列表时会有所帮助。
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121