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');
}
在类里面,我在自己的家庭小部件中调用了3次,但仅运行一次initState
。这是为什么?控制台中只能打印1张。
logo != ''
? FutureBuilder<String>(
future: storage.getVendorLogo(logo),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CustomImageRectangle(url: snapshot.data);
} else {
return CustomImageRectangle();
}
})
: CustomImageRectangle(),
最佳答案
一次未创建CustomImageRectangle
3次。有条件地渲染一次。因此,仅观察到一次打印。
在代码片段中:
logo != ''
? FutureBuilder<String>(
future: storage.getVendorLogo(logo),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CustomImageRectangle(url: snapshot.data);
} else {
return CustomImageRectangle();
}
})
: CustomImageRectangle(),
仅当FutureBuilder
为logo!=''
时,才会返回true
。在
builder
的FutureBuilder
中,if (snapshot.hasData)
将为true
或false
。取决于,将仅返回
CustomImageRectangle(url: snapshot.data)
或CustomImageRectangle()
之一。否则,如果
logo!=''
是false
,则将返回三元运算符中的CustomImageRectangle()
。在所有情况下,
CustomImageRectangle
仅创建一次。因此,仅一次调用了initState
。考虑下面的示例,该示例一次渲染3次:
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(),
],
),
),
),
);
}
}
控制台输出:null
null
null
关于flutter - 小部件的多个对象只能在Flutter中运行一次initState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63032813/