In this shot, you will learn to use the FittedBox layout widget to create responsive layouts for Flutter applications.
Focus Widget: FittedBox
The FittedBox
widget is a single child layout widget, which means it can have only one child assigned to it. In this example, the Row
widget is added as a child to the FittedBox
widget. The Row
widget has two Image
widgets as its children. Normally, the second child of the Row
widget will overflow to the right when it renders its children on a screen size that is not sufficient to accommodate all of its children. However, with FittedBox
this problem of widget overflowing is solved as it scales and positions its child within the parent widget.
FittedBox
widgetFittedBox(
child: Row(
children: [
Image.asset('assets/flutter_icon.png'),
Image.asset('assets/flutter_icon.png'),
],
),
)
import 'package:flutter/material.dart';/// FittedBox fits it child with in the given space during layout to avoid overflows.void main() => runApp(FittedBoxDemo());class FittedBoxDemo extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(debugShowCheckedModeBanner: false,home: MyFittedBox(),);}}class MyFittedBox extends StatefulWidget {@override_MyFittedBoxState createState() => _MyFittedBoxState();}int noFittedBox = 0;int withFittedBox = 1;Map<int, String> dropdown = {noFittedBox: "No FittedBox",withFittedBox: 'FittedBox',};class _MyFittedBoxState extends State<MyFittedBox> {@overridevoid didUpdateWidget(MyFittedBox oldWidget) {super.didUpdateWidget(oldWidget);}int _currentOption = 0;String dropDownValue = dropdown[0];bool isFittedBox = false;@overridevoid initState() {super.initState();updateContainer(0);}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("FittedBox Widget"),actions: [Padding(padding: const EdgeInsets.only(left: 16.0),child: DropdownButton(hint:dropDownValue == null ? Text('Select') : Text(dropDownValue),items: dropdown.keys.map((e) => DropdownMenuItem(child: Text(dropdown[e]),onTap: () {setState(() {_currentOption = e;updateContainer(_currentOption == 0? noFittedBox: withFittedBox);});},value: e,)).toList(),onChanged: (newValue) {print(newValue);dropDownValue = dropdown[newValue];},),)],),//FittedBox Widget Usagebody: isFittedBox? FittedBox(child: rowOfImages(),): rowOfImages(),);}Widget rowOfImages() {return Row(children: [Image.asset('assets/flutter_icon.png'),Image.asset('assets/flutter_icon.png'),],);}void updateContainer(int option) {switch (option) {case 0:setState(() {isFittedBox = false;});break;case 1:setState(() {isFittedBox = true;});break;}}}
Free Resources