gpt4 book ai didi

flutter - ListView 内的容器即使有高度也会扩展

转载 作者:行者123 更新时间:2023-12-02 02:19:39 26 4
gpt4 key购买 nike

ListView 中的以下容器不会有高度,即使我指定了高度。相反,它会扩展到整个 ListView 的高度

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key? key, required this.title}) : super(key: key);

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: [
Container(
width: 100,
height: 20,
color: Colors.red)
])

);
}
}

根据https://api.flutter.dev/flutter/widgets/Container-class.html ,

If the widget has no child and no alignment, but a height, width, orconstraints are provided, then the Container tries to be as small aspossible given the combination of those constraints and the parent'sconstraints.

既然容器有限制,那么它不应该尽可能小吗?

最佳答案

看看Understanding Constraints在 Flutter 文档中。

ListView 为其子级 提供的约束 过于精确地填充交叉轴。您的容器无法决定其大小超出这些约束

记住,约束下降,尺寸上升。


您应该将Containers放置在ListView内。在以下示例中,第一个 Container(红色)未定位,第二个(绿色)居中,最后一个(蓝色)对齐 > 在 topLeft 上:

CenterAlign 小部件都将采用最大高度,并为它们的子部件(您的Container)提供灵活性。

enter image description here

完整源代码:

import 'dart:math' show Random;

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key? key, required this.title}) : super(key: key);

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.grey.shade200,
child: ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: [
Container(width: 100, height: 20, color: Colors.red),
Center(
child: Container(width: 100, height: 10, color: Colors.green),
),
Align(
alignment: Alignment.topLeft,
child: Container(width: 100, height: 20, color: Colors.blue),
),
],
),
),
);
}
}

关于flutter - ListView 内的容器即使有高度也会扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66616809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com