如何在颤振中应用MVC或设计模式?

时间:2019-10-16 13:58:13

标签: flutter dart

我正在尝试使用local_auth软件包包括生物识别身份验证。在应用启动时使用。指纹用于确定用户是否是手机的所有者。如果确认,将进入主页。波纹管代码有效,但我要在波纹管代码上使用的是MVCdesign pattern。有人可以引导我吗?

class LoginOptionState extends State<LoginOption> {
  final LocalAuthentication auth = LocalAuthentication();
  String _authorized = 'Not Authorized';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: new Container(
            child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new Column(
            children: <Widget>[
              Text("Touch ID"),
              SizedBox(height: 10),
              GestureDetector(
                  child: Image.asset(
                    "assets/",
                  ),
                  onTap: _authenticate),
            ],
          ),
        ],
      ),
    )));
  }

  Future<void> _authenticate() async {
    bool authenticated = false;
    try {
      authenticated = await auth.authenticateWithBiometrics(
          localizedReason: 'Scan your fingerprint to authenticate',
          useErrorDialogs: true,
          stickyAuth: false);
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _authorized = authenticated
          ? Navigator.pushNamed(context, homePageViewRoute)
          : 'Not Authorized';
    });
  }
}

2 个答案:

答案 0 :(得分:1)

使用Greg Perry mvc_pattern的出色库。链接上提供了快速入门示例代码和说明。

如上所示,是上面链接中经典计数器应用程序的快速入门示例:

视图:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

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

  // Fields in a Widget subclass are always marked "final".

  static final String title = 'Flutter Demo Home Page';

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final Controller _con = Controller.con;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              widget.title,
            ),
            Text(
              '${_con.counter}',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(
              _con.incrementCounter
          );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

控制器类:

class Controller extends ControllerMVC {
  /// Singleton Factory
  factory Controller() {
    if (_this == null) _this = Controller._();
    return _this;
  }
  static Controller _this;

  Controller._();

  /// Allow for easy access to 'the Controller' throughout the application.
  static Controller get con => _this;

  int get counter => _counter;
  int _counter = 0;
  void incrementCounter() => _counter++;
}

现在将上面的代码重构,以添加模型:

int get counter => Model.counter;
  void incrementCounter() {
    /// The Controller knows how to 'talk to' the Model. It knows the name, but Model does the work.
    Model._incrementCounter();
  }

最后是模型类:

class Model {
  static int get counter => _counter;
  static int _counter = 0;
  static int _incrementCounter() => ++_counter;
}

但是,请确保将flutter升级到1.13.0版。至少对我而言,我在较低版本中遇到了一些构建错误。

答案 1 :(得分:0)

Karee 是一套在 Flutter 中实现 MVC 设计的工具。它可以帮助您管理控制器、路线、屏幕等。请参阅 karee github wiki 以获取文档。

您可以使用 Karee 。支持 Flutter 2.X.X

安装运行 npm install -g karee 然后karee create 在基于 Karee 创建一个 New Flutter 项目后,您可以添加新的控制器

示例代码

创建新控制器

    Karee generate --controller --path auth Authentication

lib/app/controllers/auth/AuthenticationController下生成的文件

@Controller
class AuthenticationController {

       login(username, password) {

                /// Your custom code

       }
}

添加路线

   Route.on('/login', 'AuthenticationController@login');

在屏幕上使用

   var authUser = KareeRouter.goto('/login', parameter:[username, password]);