Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent for `componentDidMount()` in Flutter

I coming from ReactJS and React Native. I want to try out Flutter. So far I want to have a login screen. Therefore I want to check if a user is already logged in. If so forward to the Home Screen. If not, show the login screen.

In React with TypeScript and Firebase I would to it this way:

interface RootScreenState {
  isLoading: boolean;
  user: firebase.User | null;
}

class RootScreen extends React.Component<{}, RootScreenState> {

  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      user: null
    }
  }

  componentDidMount() {

    // make an async call to some firebase libraries to look for stored user credentials
    // if some credentials are found try to login
    // of no credentials are found or login fails return null
    // otherwise the user is returned
    tryToLogin().then((currentUser: firebase.User | null) => {
      this.setState({
        isLoading: false,
        user: currentUser
      }).catch(err => { /* do some error handling */});
  }

  render() {
    const { isLoading, user } = this.state;

    if(isLoading) return ( /* loading screen */ );
    else if(user === null) return ( /* login screen */ );
    else return ( /* home screen */ );
  }
}

How do I do with Flutter? I could not find anything about an equivalent to compnentDidMount(), should I do it in the constructor? In React this would fail.

like image 342
0x4b50 Avatar asked Dec 23 '22 18:12

0x4b50


1 Answers

use initState in Stateful widget.InitState is called when the stateful widget is first time painted. For ex

class _MyAppState extends State<MyApp> {
  Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
like image 149
Rajneesh Chaurasia Avatar answered Jan 01 '23 09:01

Rajneesh Chaurasia