ConstrainedBox是flutter SDK 中的内置小部件。它的函数是为其子小部件添加大小限制。如果我们希望容器或图像不超过特定的高度和宽度,这将非常方便。通过使Text小部件成为ConstrainedBox上的子部件,将文本保留在包装布局中也很好。此功能也可以在 SizedBox 小部件或其他地方找到。
ConstrainedBox 类的构造函数:
ConstrainedBox(
{Key key,
@required BoxConstraints constraints,
Widget child}
)
ConstrainedBox 小部件的属性:
- 约束:该属性将BoxConstrain类作为对象。它使用BoxConstraints类的函数来约束它的子小部件。
示例 1:
Dart
import 'package:flutter/material.dart';
//imported googles material design library
void main() {
runApp(
/**Our App Widget Tree Starts Here**/
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
centerTitle: true,
), //AppBar
body: Center(
/** ConstrainedBox Widget **/
child: ConstrainedBox(
constraints: BoxConstraints.expand(height: 200, width: 200),
child: Container(
color: Colors.green,
), //Conatiner widget
), //ConstrainedBox
), //Center
), //Scaffold
), //MaterialApp
);
}
Dart
import 'package:flutter/material.dart';
//imported googles material design library
void main() {
runApp(
/**Our App Widget Tree Starts Here**/
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
centerTitle: true,
), //AppBar
body: Center(
/** ConstrainedBox Widget **/
child: ConstrainedBox(
constraints: BoxConstraints.expand(height: 200, width: 200),
child: Text(
'A Computer Science portal for geeks. It contains well
written,well thought and well explained computer science
and programmingarticles, quizzes, interview experiences
and much more.',
style: TextStyle(fontSize: 15),
), //Text
), //ConstrainedBox
), //Center
), //Scaffold
), //MaterialApp
);
}
输出:
说明:在这个flutter应用中,我们可以看到ConstrainedBox Widget 用于约束其子 Widget 的高度和宽度,它是一个Container 。这里我们使用了BoxConstraines.expended并将 height 和 width 参数设置为 200。我们可以注意到,在 Container 小部件中没有提到高度和宽度参数,它只是扩展以填充其父小部件。
示例 2:
Dart
import 'package:flutter/material.dart';
//imported googles material design library
void main() {
runApp(
/**Our App Widget Tree Starts Here**/
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
centerTitle: true,
), //AppBar
body: Center(
/** ConstrainedBox Widget **/
child: ConstrainedBox(
constraints: BoxConstraints.expand(height: 200, width: 200),
child: Text(
'A Computer Science portal for geeks. It contains well
written,well thought and well explained computer science
and programmingarticles, quizzes, interview experiences
and much more.',
style: TextStyle(fontSize: 15),
), //Text
), //ConstrainedBox
), //Center
), //Scaffold
), //MaterialApp
);
}
输出:
说明:在这个flutter应用程序中, ConstrainedBox小部件用于将文本包装在 200 X 200 的框中。这里的文本也扩展为BoxConstraints填充框。展开使用。当我们希望我们的文本不会溢出某个有界区域时, ConstrainedBox小部件的这个应用程序非常有用。