【问题标题】:Pass variable to a Widget outside Stateful class将变量传递给有状态类之外的小部件
【发布时间】:2019-06-07 23:46:47
【问题描述】:

将变量 (photoUrl) 传递给 Widget 的最佳方式是什么? 在状态类中添加小部件它说:在初始化程序中只能访问静态成员。

将方法更改为静态也不能解决我的问题。

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),
      ),
    ),
  );
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您在初始化程序中调用了accountPage(),但photoUrl 仅在initState() 上设置,因此即使accountPage() 可以访问photoUrl,它也会得到错误的值。

    我建议如下:

    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),
          ),
        ),
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2015-04-17
      • 1970-01-01
      • 2020-12-01
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多