flutter - 如何在扩展的 Flutter 列表中指定元素的宽度?
问题描述
下面的代码表示一个项目列表,其中列表应该是全宽的,但列表中的元素可能不是。Flutter 似乎忽略了我对 的宽度限制SizedBox
并强制它完全扩展。
class ExampleBadListWidth extends StatelessWidget {
List<String> things = [
"1: This is a really really really really really really really really really really long thing",
"2: This is a really really really really really really really really really really long thing",
"3: This is a really really really really really really really really really really long thing"
];
ExampleBadListWidth();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Expanded(
child: ListView.builder(
itemCount: things.length,
itemBuilder: _thingBuilder,
))
]));
}
Widget _thingBuilder(context, index) {
return SizedBox(width: 100, child: Text(things[index]));
}
}
解决方案
您可以在下面复制粘贴运行完整代码您可以使用或
包装SizedBox
Center
Align
代码片段
Widget _thingBuilder(context, index) {
return Center(
child: SizedBox(
width: 100,
child: Text(things[index])),
);
}
或者
Widget _thingBuilder(context, index) {
return Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: 100,
child: Text(things[index])),
);
}
工作演示
完整代码
import 'package:flutter/material.dart';
class ExampleBadListWidth extends StatelessWidget {
List<String> things = [
"1: This is a really really really really really really really really really really long thing",
"2: This is a really really really really really really really really really really long thing",
"3: This is a really really really really really really really really really really long thing"
];
ExampleBadListWidth();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Expanded(
child: ListView.builder(
itemCount: things.length,
itemBuilder: _thingBuilder,
))
]));
}
Widget _thingBuilder(context, index) {
return Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: 100,
child: Text(things[index])),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ExampleBadListWidth(),
);
}
}
推荐阅读
- javascript - 使用 touchmove 事件检测哪个 div 手指结束
- docker - 在 docker-compose up 之后添加音量
- javascript - 我想为从 mysql 数据库登录的每个用户发送唯一记录
- c - 调用fork时是否复制线程?
- phpstorm - PhpStorm - 同时显示项目文件和结构
- android - 当人们安装我的应用程序时,他们会获得两个应用程序
- masstransit - 是否可以连接到特定队列并读取指定数量的消息?
- multithreading - 使用 Logback 记录线程 ID 而不是线程名称
- r - 世界地图上的条形图
- python - 代码问题-> Python 识别报纸上的人脸