In this article, I'm going to share how to resize a Container irrespective of its child widgets in Flutter.
Let's see this step by step. The soultion to this problem is there in step3 and full code is at the bottom of the page.
1) First, we will create a container with a green background. You can observe that the whole background is green now.
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Container Example"),
),
body: Center(
child: Container(
color: Colors.green,
),
)),
);
}
}
2) After a Text is added to the container. It gets resized as its child size.
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Expand Button Example"),
),
body: Center(
child: Container(
color: Colors.green,
child: Text('Hello'),
),
)),
);
}
}
3) Now in order to expand the container irrespective of its child elements. You need to wrap the Container insize a FractionallySizedBox.
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Container Example"),
),
body: Center(
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.5,
child: Container(
color: Colors.green,
child: Center(child: Text('Hello')),
)
),
)),
);
}
}
Well, this is how you can resize the container irrespective of its child.
Here is the full code from main.dart file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Container Example"),
),
body: Center(
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.5,
child: Container(
color: Colors.green,
child: Center(child: Text('Hello')),
)
),
)),
);
}
}
Thanks,
Srikanth