Flutter trick: using LayoutBuilder for responsive designs.
When you’re building apps that need to work across different screen sizes (phones, tablets, etc.), LayoutBuilder is a powerful tool to help create adaptive UIs. It lets you access the parent widget’s constraints and make dynamic decisions based on the available space.
Example: Responsive Grid Layout
In this example, we create a grid layout that adjusts the number of columns based on the screen width:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Responsive Grid")),
body: ResponsiveGrid(),
),
);
}
}
class ResponsiveGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
// Check the screen width to decide number of columns
int columns = constraints.maxWidth > 600 ? 4 : 2;
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: 20,
itemBuilder: (context, index) {
return Container(
color: Colors.blueAccent,
child: Center(
child: Text(
"Item $index",
style: TextStyle(color: Colors.white),
),
),
);
},
);
},
);
}
}
Explanation
AnimationController: Controls the animation’s duration and state (we set it to repeat indefinitely here).
AnimatedBuilder: Efficiently rebuilds only the parts of the widget that need updating, keeping performance smooth.
Transform.rotate: Rotates the icon based on the controller’s current animation value.
Using AnimatedBuilder like this is a highly efficient way to add animations to your Flutter app without rebuilding the widget tree, which keeps animations smooth and improves app performance.