流程如下

  1. 进入App,判断当前用户的登录情况
  2. 如果已登录,则进入HomePage
  3. 如果没有登录,则进入登录页
  4. 在登录页点击登录,将当前用户设置为已登录

需要安装的包

  mobx:  
  flutter_mobx:  
  provider:

Mobx文档

user.dart

import 'package:mobx/mobx.dart';

// Include generated file
part 'user.g.dart';

// This is the class used by rest of your codebase
class User = _User with _$User;


// The store-class
abstract class _User implements Store {

  @observable
  bool loggedIn = false;

  @action
  void login() {
      loggedIn = true;
  }

}

其中有一个属性表示当前用户是否已登录,以及一个action来将用户的登录状态设置为是

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import './pages/login.dart';
import 'package:provider/provider.dart';
import 'store/user.dart';

@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: Provider<User>(
      builder: (_) => User(),
      child: Entry(),
    ),
    routes:  <String, WidgetBuilder> {
    },
  );
}

class Entry extends StatefulWidget {
  const Entry({Key key}) : super(key: key);

  @override
  _EntryState createState() => _EntryState();
}

class _EntryState extends State<Entry> {
  @override
  Widget build(BuildContext context)  { 
    final user = Provider.of<User>(context); // access User store from the parent widget

    return Observer(
     builder: (_) => user.loggedIn ? MyHomePage() : Login(),
     );
   }
}
...

这里重点是Provider这个控件,这个是用来确保整个项目的user用的是一个对象,之后在项目的任何地方都可以通过Provider.of<User>(context)来调用user实例

login.dart

class Login extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
     final user = Provider.of<User>(context); // access User store from the parent widget
     return Scaffold(
      appBar: AppBar(
        title: Text("login")
      ),
      body: Center(
        child: RaisedButton(onPressed: user.login),
      )
    );
  }
}

点击后,组件会变成你的Homepage