Sobes.tech
Middle

Which widgets in Flutter provide responsive layout?

sobes.tech AI

Answer from AI

  • MediaQuery - for obtaining information about the size and orientation of the screen.
  • LayoutBuilder - for building widgets based on the constraints of the parent widget.
  • OrientationBuilder - for building widgets depending on the screen orientation.
  • FractionallySizedBox - for creating elements with size proportional to the available space.
  • AspectRatio - for maintaining a specified aspect ratio of an element.
  • Expanded and Flexible - for flexible distribution of space among elements in a Row or Column.
  • SingleChildScrollView - for scrolling content if it exceeds the available area.
  • ListView and GridView - for displaying lists and grids with adaptability.
  • ResponsiveBuilder (from the responsive_framework package) - for building widgets based on breakpoints.
  • FittedBox - for scaling a child widget according to the size of the parent.
// Example of using MediaQuery
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive Design'),
      ),
      body: Center(
        child: Text('Screen size: ${screenSize.width.toStringAsFixed(1)}x${screenSize.height.toStringAsFixed(1)}'),
      ),
    );
  }
}
// Example of using LayoutBuilder
class AdaptiveContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        if (constraints.maxWidth > 600) {
          // Wide screen
          return Container(
            color: Colors.blue,
            width: 300,
            height: 100,
            child: Center(child: Text('Wide')),
          );
        } else {
          // Narrow screen
          return Container(
            color: Colors.red,
            width: 100,
            height: 50,
            child: Center(child: Text('Narrow')),
          );
        }
      },
    );
  }
}
// Example of using Expanded
class FlexibleLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          color: Colors.yellow,
          width: 50,
          height: 50,
        ),
        Expanded( // Will take the remaining space
          child: Container(
            color: Colors.green,
            height: 50,
          ),
        ),
      ],
    );
  }
}
Which widgets in Flutter provide responsive layout… - sobes.tech