Implement login function

To prevent the user from logging in to the application through the login interface and still returning to the login interface after pressing the back key, we need to create a new routing stack after the user logs in

Directly on the code, program entry:

void main() {
  DataUtils.getUserInfo().then((userInfo) {
    runApp(MyApp(userInfo));
  });
}

class MyApp extends StatelessWidget {
  MyApp(this.userModel);

  final UserModel userModel;

  @override
  Widget build(BuildContext context) {
    GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
    return MaterialApp(
      title: 'MaterialManagement',
      theme: ThemeData(accentColor: Colors.white, primaryColor: Colors.blue),
      home: userModel == null
          ? LoginPage()
          : HomePage(),
      routes: <String, WidgetBuilder>{
        '/login': (BuildContext context) => LoginPage(),
        '/home': (BuildContext context) => HomePage() }, ); }}Copy the code

Now we are going to define a loginButton _loginWithAvatarAndPassword onPressed event callback function to do to create routing of the stack, so you can avoid after login successful press the return key to return to the login interface issues (cancellation of the same) :

Future<dynamic> _loginWithAvatarAndPassword() async {
        final form = _formKey.currentState;
        if (form.validate()) {
          _formKey.currentState.save();
          LoginUtils.login(user.avatar, user.password, (isAlive, userInfo) {
            if (isAlive) {
              runApp(MyApp(userInfo)); // look here!}}); }}Copy the code

Double-click to exit the application

WillPopScope registers a callback to onWillPop with custom user actions on routing

Customize our callback function,

Future<bool> _doubleExit() {
    int nowTime = new DateTime.now().microsecondsSinceEpoch;
    if(_lastClickTime ! =0 && nowTime - _lastClickTime > 1500) {
      return new Future.value(true);
    } else {
      _lastClickTime = new DateTime.now().microsecondsSinceEpoch;
      new Future.delayed(const Duration(milliseconds: 1500), () {
        _lastClickTime = 0;
      });
      return new Future.value(false); }}Copy the code

Nested the pre-created child _getBody() in WillPopScope

Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _doubleExit, // look here!
      child: _getBody(),
    );
  }
Copy the code