在Column中通过设置mainAxisSize: MainAxisSize.min
可以使Column自适应子节点的高度,例如:
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: Scaffold(
body: Container(
color: Colors.red,
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('text'),
],
)),
),
);
}
}
效果图:
但是如果放在TabBarView
下面的话,就没用了,会填满整个屏幕,示例代码:
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: Scaffold(
body: DefaultTabController(
length: 2,
child: Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(56),
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "tab1",
),
Tab(
text: "tab2",
),
],
),
)),
body: TabBarView(
children: [
Container(
color: Colors.red,
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('text'),
],
)),
Container(
color: Colors.blue,
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Text('text'),
],
),
),
],
),
),
),
),
);
}
}
效果图:
这种情况下要怎么才能让Column的高度自适应呢?
TabbarView下的widget默认会包一曾Expanded, 所以你的Container的确是占满屏幕的,可是Column不影响吧?
Column下的MainAxisSize.min还是会生效的。