紧约束(Tight Constraints)
定义:紧约束指的是父组件对其子组件施加了严格的大小限制。例如,如果一个父组件给子组件提供了具体的宽度和高度,那么子组件只能在这个范围内绘制。
例子:使用 SizedBox、Container 指定 width 和 height。
例子
不使用ConstrainedBox
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: Container(
color: Colors.blue,
width: 59,
height: 50,
),
),
);
}
}
使用ConstrainedBox
import 'package:demo/pages/home_page.dart';
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 25,
maxHeight: 25,
),
child: Container(
color: Colors.blue,
width: 59,
height: 50,
),
),
),
);
}
}
import 'package:demo/pages/home_page.dart';
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 200,
minHeight: 200
),
child: Container(
color: Colors.blue,
width: 100,
height: 100,
),
),
),
),
);
}
}
import 'package:demo/pages/home_page.dart';
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: const BoxConstraints.tight(Size(200, 200)),
child: Container(
color: Colors.blue,
width: 100,
height: 100,
),
),
),
),
);
}
}