MainApp根据值发送到页面

时间:2018-12-06 15:04:04

标签: dart flutter

我正在构建Flutter应用程序,当该应用程序启动时,我想将用户发送到登录页面(如果尚未登录)或仪表板页面(如果已登录)。

基本上,main()只是代码,没有小部件。我该怎么办?

我在想类似的东西:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new StarterPoint()
  ));
}

class StarterPoint extends StatelessWidget {
  final bool loggedIn = false;

    if (loggedIn) {
      Navigator.push(
        MaterialPageRoute(builder: (context) => Dashboard()),
      );
    } else {
            Navigator.push(
        MaterialPageRoute(builder: (context) => Login()),
      );
    }
}

1 个答案:

答案 0 :(得分:0)

这是您可以做什么的简单示例。我认为您需要根据是否登录来跟踪StarterPoint中的状态。

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: StarterPoint()));
}

class StarterPoint extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => StarterPointState();
}

class StarterPointState extends State<StarterPoint> {
  bool loggedIn = false;

  @override
  Widget build(BuildContext context) {
    if (loggedIn) {
      return Dashboard();
    } else {
      return Login(() => setState(() {
            loggedIn = true;
          }));
    }
  }
}

class Dashboard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('hello!');
  }
}

class Login extends StatelessWidget {
  final Function() callBack;
  Login(this.callBack);

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      RaisedButton(child: Text('press'), onPressed: () => callBack())
    ]);
  }
}