Flutter中StatelessWidget调用StatefulWidget的函数

Posted

技术标签:

【中文标题】Flutter中StatelessWidget调用StatefulWidget的函数【英文标题】:Call function of StatefulWidget from StatelessWidget in Flutter 【发布时间】:2021-06-24 22:49:24 【问题描述】:

当我的 StatelessWidget 中的按钮被按下时,我想从我的 StatefulWidget 调用一个函数。在下面的代码中,您可以看到我正在尝试做什么。我不太确定它是如何工作的,所以也许你可以帮助我。

StatelessWidget - 按钮应该从 StatefulWidget 调用函数

class HomeWidget extends StatelessWidget 

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Column(
        children: [
          SafeArea(child: Column(
            children: [
              Padding(
                padding: EdgeInsets.all(10),
                child: ProgressButton.icon(iconedButtons: not needed
                    onPressed: addUser,
                    state: ButtonState.idle),
              ),
            ],
          )),
        ],
      ),
    );
  

Statefulwidget - addUser() 应该由 StatelessWidget 调用

class HomeStateful extends StatefulWidget 
  @override
  _HomeStatefulState createState() => _HomeStatefulState();


class _HomeStatefulState extends State<HomeStateful> 
  final firestoreInstance = FirebaseFirestore.instance;
  CollectionReference users = FirebaseFirestore.instance.collection('users');
  int _currentIndex = 0;

  final List<Widget> _children = [
    HomeWidget(),
    MessageWidget(),
  ];

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      backgroundColor: Colors.white,
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: onTabTapped,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text("Home"),
              backgroundColor: Colors.blue,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.mail),
              title: Text("Nachrichten"),
              backgroundColor: Colors.blue,
            ),
          ]),
    );
  

  void onTabTapped(int index) 
    setState(() 
      _currentIndex = index;
    );
  

  void addUser() 
    firestoreInstance.collection("users").add(
      "vorname": prenameController,
      "nachname": nameController,
      "geburtstag": birthdayController,
      "adresse": adressController,
      "telefon": numberController,
      "id": 0
    );
  


【问题讨论】:

【参考方案1】:

你可以在无状态小部件中使用回调函数,像这样

class HomeWidget extends StatelessWidget 
  const HomeWidget(Key key, @required this.addUser) : super(key: key);

  /// If you want to pass any value back, then you can use something
  /// like this
  /// final Function(User user) addUser;

  /// VoidCallback as name speaks its a empty fn.
  final VoidCallback addUser; // ==> Here is the answer.

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Column(
        children: [
          SafeArea(
              child: Column(
            children: [
              Padding(
                  padding: EdgeInsets.all(10),
                  child: RaisedButton(
                    onPressed: addUser, // Add User fun here
                  )),
            ],
          )),
        ],
      ),
    );
  

并且在有状态/父小部件中。

class MyHomePage extends StatefulWidget 
  @override
  _MyHomePageState createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> 
 
  final _list = <Widget>[
    HomeWidget(addUser: addUser) // Wrong, You cannot access the addUser here.
  ];

   final _childList = <Widget>[];// But you can initialize here and add the HomeWidget in initState.
  

  @override
  void initState() 
    super.initState();
    _childList.addAll([
      HomeWidget(addUser: addUser),
      HomeWidget(addUser: addUser),

      ///... Other children
    ]);
  

  void addUser() 
    // Do Somethign
  

  @override
  Widget build(BuildContext context) 
    return Column(
      children: [
        HomeWidget(addUser: addUser),
      ],
    );
  

【讨论】:

我现在尝试将它实施到我的项目中。似乎可以工作,但有一个错误:final List&lt;Widget&gt; _children = [ HomeWidget(addUser: addUser), MessageWidget(), ]; - 所以我尝试按照所述在我的 StatefulWidget 中使用该功能。错误:无法在初始化程序中访问实例成员“addUser”。我该如何解决?

以上是关于Flutter中StatelessWidget调用StatefulWidget的函数的主要内容,如果未能解决你的问题,请参考以下文章

StatefulWidget 和 StatelessWidget 的 Flutter 性能

如何在 StatelessWidget 中更改 StatefulWidget 的状态?

Flutter生命周期

Flutter控件——常用控件:StatelessWidget和Context

Flutter 页面生命周期

Flutter ValueNotifier 倒计时 局部刷新组件 在StatelessWidget 中刷新倒计时