Reputation: 19434
class CustomImageRectangle extends StatefulWidget {
final String url;
const CustomImageRectangle({Key key, this.url}): super(key: key);
@override
_CustomImageRectangleState createState() => _CustomImageRectangleState();
}
class _CustomImageRectangleState extends State<CustomImageRectangle> {
@override
void initState() {
super.initState();
print(widget.url != null?'not null':'null');
}
Above class, I called 3 times in my home widget, but only one-time run initState
. why is that?
only 1 print in the console.
logo != ''
? FutureBuilder<String>(
future: storage.getVendorLogo(logo),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CustomImageRectangle(url: snapshot.data);
} else {
return CustomImageRectangle();
}
})
: CustomImageRectangle(),
Upvotes: 0
Views: 697
Reputation: 1288
CustomImageRectangle
isn't being created 3 times at once. It is being conditionally rendered once. Hence only once print is observed.
In the code snippet :
logo != ''
? FutureBuilder<String>(
future: storage.getVendorLogo(logo),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CustomImageRectangle(url: snapshot.data);
} else {
return CustomImageRectangle();
}
})
: CustomImageRectangle(),
The FutureBuilder
will only be returned if logo!=''
is true
.
In the builder
of FutureBuilder
, either if (snapshot.hasData)
will be true
or false
.
Depending on that only one of the CustomImageRectangle(url: snapshot.data)
or CustomImageRectangle()
will be returned.
Otherwise if logo!=''
is false
the CustomImageRectangle()
in the ternary operator will be returned.
Here CustomImageRectangle
is created only once in all cases. Hence only once the initState
is called.
Consider the below example where it is rendered 3 times at once:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Column(
children: [
CustomImageRectangle(),
CustomImageRectangle(),
CustomImageRectangle(),
],
),
),
),
);
}
}
Console Output:
null
null
null
Upvotes: 1