SizedBox widget view in flutter is used to create box with specified width and height. If we put the SizedBox under another widget as child view then it can only be sized max as its parent widget. The default value of height and width is Zero in SizedBox. We would also used Container widget in this tutorial. Both SizedBox and Container widgets works same in flutter. So in this tutorial we would Create Fixed Width Height Size View using SizedBox and Container Widget in flutter android iOS app example.
Contents in this project Flutter Create Fixed Width Height Size View using SizedBox and Container Widget in Android iOS:
1. Import material.dart package in your app’s main.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Call our main MyApp class using void main runApp() function.
1 |
void main() => runApp(MyApp()); |
3. Create our main MyApp class extends with StatelessWidget.
1 2 3 4 |
class MyApp extends StatelessWidget { } |
4. Create Widget Build method in MyApp class and inside home section first create Scaffold widget. Then in Scaffold widget create SafeArea widget. Now we would define the Center widget in SafeArea widget. Finally we would put a Column widget in Center widget. Column widget can hold multiple children.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Center( child: Column( children: [ ] ) ) ) ) ); } } |
5. Create Container widget in Column widget with Green background color. As you can see in below code we have defined fixed height and width as 150 pixels. You can also add another widget here using child.
1 2 3 4 5 6 |
Container( height: 150.00, width: 150.00, color: Colors.green, //Put your child widget here. ), |
6. Create SizedBox widget in Column widget after Container. SizedBox support fixed width and height. It did not directly supports background color so we are using Decorate box to setting up background of SizedBox widget.
1 2 3 4 5 6 7 8 9 10 |
SizedBox( width: 220.00, height: 220.00, child: const DecoratedBox( decoration: const BoxDecoration( color: Colors.lightBlueAccent, ), // Put Your Child widget here. ), ), |
7. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Center( child: Column( children: [ Container( height: 150.00, width: 150.00, color: Colors.green, //Put your child widget here. ), SizedBox( width: 220.00, height: 220.00, child: const DecoratedBox( decoration: const BoxDecoration( color: Colors.lightBlueAccent, ), // Put Your Child widget here. ), ), ] ) ) ) ) ); } } |
Screenshot: