[英]Pass variable to a Widget outside Stateful class
What is the best way to pass variable (photoUrl) to a Widget? 将变量(photoUrl)传递到小部件的最佳方法是什么? Adding widget inside state class it says: Only static members can be accessed in initializers.
在状态类中添加小部件时,它说:在初始化器中只能访问静态成员。
Changing method to static neither solves my issue. 将方法更改为static不能解决我的问题。
class _ABState extends State<AB> {
int _selectedPage = 0;
String photoUrl; /* Value set in initState()*/
/* To switch between pages */
final _pageOptions = [
Text('Page 1'),
accountPage(), /* Page 2 */
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pageOptions[_selectedPage],
);
}
}
/* Widget outside class requires photoUrl */
Widget accountPage() {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(photoUrl),
),
),
);
}
You are calling accountPage()
at the initializer, but photoUrl
is set only on initState()
, so even if accountPage()
had access to photoUrl
, it would get the wrong value. 您正在初始化器上调用
accountPage()
,但是photoUrl
仅在initState()
上设置,因此,即使accountPage()
可以访问photoUrl
,它也会得到错误的值。
I suggest the following: 我建议以下内容:
class _ABState extends State<AB> {
int _selectedPage = 0;
String photoUrl;
List<Widget>_pageOptions;
@override
void initState() {
super.initState();
photoUrl = "<PLACE_YOUR_VALUE>";
_pageOptions = [
Text('Page 1'),
accountPage(photoUrl),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pageOptions[_selectedPage],
);
}
}
Widget accountPage(String photoUrl) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(photoUrl),
),
),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.