Flutter Builder widget is helpful and simple to use.
There are two cases where you may use builder widget.
- Get the context of the parent widget and use that widget to do things
- If you wanna do a lot of conditional check and then build your widget
Here we have an example that takes parent widget’s context and build the UI.
void main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'dbestech',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage(),
);
}
}
// Home Page
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
var size = MediaQuery.of(context).size.width;
double fontSize=20;
if(size>770){
fontSize=30;
}
return Text(
"Builder",
style: TextStyle(
fontSize: fontSize
),
);
}
),
),
);
}
}
Here you see for builder property we are passing a function with context and then returning a widget.
This Builder widget helps to do some conditional check and statement inside the builder property.
This is one of the very few helpful widgets that helps you to do conditional check and do extra calculation inside UI.
Builder(
builder: (_) {
final AuthController _auth = Get.find();
final user = _auth.getUser();
String _label = ' Hello mate';
if (user != null) {
_label = ' Hello ${user.displayName}';
}
return Text(_label,
style: kDetailsTS.copyWith(
color: kOnSurfaceTextColor));
},
),
See how a builder widget return a Text Widget. Before we returned the Text widget we access our controller and doing conditional check.
So you could use Builder widget inside Row, Column or Stack widget.