Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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),
          ),
        ),
      ),
    );
  }
}
like image 320
Tegster007 Avatar asked Aug 07 '18 07:08

Tegster007


1 Answers

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().

like image 69
Marcin Szałek Avatar answered Sep 25 '22 00:09

Marcin Szałek