Accessing a function of stateful widget in its state class? flutter

邮差的信 提交于 2019-12-11 02:52:02

问题


I am trying to call _signOut function after the onPressed method for logout button. However it doesnt (recognize the function or let me call it) I can however make a call widget.Onsignedout, a callback to it parent and everything works as intended. except i sign out the user at auth.signout and call back is just to update the form. how can I access the _signOut() from state class? thank you

import 'package:flutter/material.dart';
import 'package:login_demo/auth.dart';
import 'package:login_demo/root_page.dart';

class HomePage extends StatefulWidget {
  HomePage({this.auth, this.onSignedOut});
  final BaseAuth auth;
  //To call a function of a parent, you can use the callback pattern
  final VoidCallback onSignedOut;

  void _signOut() async {
    try {
      Text('Signing Out here');
      await auth.signOut();
      onSignedOut;
    } catch (e) {
      print(e);
    }
  }

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Homepage'),
        actions: <Widget>[
          FlatButton(
            child: Text(
              'Logout',
              style: TextStyle(fontSize: 17.0, color: Colors.white)
            ),
            onPressed: widget.onSignedOut,
          ),
        ],
      ),
      body: Container(
        child: Center(
          child: Text(
            'Welcome',
            style: TextStyle(fontSize: 32.0),
          ),
        ),
      ),
    );
  }
}

回答1:


You need to make your method public. Right now because of the underscore (_) before the name, the method is private and you cannot access it.

Simply change the name from _signOut to signOut and then you should be able to call it by widget.signOut().



来源:https://stackoverflow.com/questions/51720835/accessing-a-function-of-stateful-widget-in-its-state-class-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!