Flutter 中`componentDidMount()` 的等价物是什么

0x4*_*b50 3 state dart reactjs react-native flutter

我来自 ReactJS 和 React Native。我想试试 Flutter。到目前为止,我想要一个登录屏幕。因此,我想检查用户是否已经登录。如果是,则转到主屏幕。如果没有,请显示登录屏幕。

在 React 与 TypeScript 和 Firebase 中,我会这样:

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 */ );
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何处理 Flutter?我找不到任何与 等效的东西compnentDidMount(),我应该在构造函数中做吗?在 React 中这会失败。

Raj*_*sia 7

在有状态小部件中使用 initState.InitState 在有状态小部件第一次绘制时被调用。前任

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

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
Run Code Online (Sandbox Code Playgroud)

  • Flutter 文档应该在 [React Native 开发人员部分](https://flutter.dev/docs/get-started/flutter-for/react-native-devs#react-native-and-flutter-widget-equivalent-成分)。还是我错过了?不管怎么说,还是要谢谢你 (2认同)