In general use Builder inline when creating your widget tree in a build
method. This is usually helpful when you need access to a context
in your widgets subtree. for example:
Also see this SO question
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: Builder(builder: (thisLowerContext) {
return RaisedButton(
onPressed: () => Scaffold.of(thisLowerContext)
.showSnackBar(SnackBar(content: Text("button was clicked"))));
}));
}
Use StatefulBuilder when you need access to the setState of that subtree. This will rebuild only the StatefulBuilder
with its subtree.
class _SomeWidgetState extends State<HomeScreen> {
Data data;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: StatefulBuilder(builder: (thisLowerContext, innerSetState) {
if (data == null) {
return RaisedButton(
child: Text("Load data"),
onPressed: () async {
Scaffold.of(thisLowerContext)
.showSnackBar(SnackBar(content: Text("Loading data...")));
var loadedData = await _loadData();
innerSetState(() => data = loadedData);
});
} else {
return RaisedButton(
child: Text("Reload data"),
onPressed: () async {
Scaffold.of(thisLowerContext).showSnackBar(
SnackBar(content: Text("Reloading data...")));
var loadedData = await _reloadData();
innerSetState(() => data = loadedData);
});
}
}));
}
}