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

4,110

Solution 1

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

Solution 2

You can do this in Flutter's initState. It gets called first when your widget tree is rendered.

Check the code below:

  @override
  void initState() {
    super.initState();
  }

For more details on various things in React Native you wished to know in Flutter. See the link below: It is the official documentation of people coming to Flutter from a React Native background.

Documentation

I hope this helps.

Share:
4,110
0x4b50
Author by

0x4b50

Updated on December 20, 2022

Comments

  • 0x4b50
    0x4b50 over 1 year

    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.