简体   繁体   English

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

[英]How to apply MVC or design pattern in flutter?

I am trying to include biometric authentication using local_auth package.我正在尝试使用local_auth package 包括生物特征认证。 This is used when the app starts.这在应用程序启动时使用。 The fingerprint is used to determine whether the user is the owner of the phone.指纹用于确定用户是否是手机的所有者。 If it is confirmed, they will be taken to the home page.如果确认,他们将被带到主页。 The below code works but what I would like to apply on the below code is MVC or design pattern .下面的代码有效,但我想在下面的代码上应用的是MVCdesign pattern Can someone guide me?有人可以指导我吗?

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';
    });
  }
}

Use the excellent library by Greg Perry mvc_pattern .使用 Greg Perry mvc_pattern的优秀库。 Quick start sample code and explanation is provided on the link.链接上提供了快速启动示例代码和说明。

As suggested here is a quick start example of the classic counter app, from the link above:正如这里所建议的,是经典计数器应用程序的快速启动示例,来自上面的链接:

The view:风景:

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),
      ),
    );
  }
}

Controller class: Controller class:

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++;
}

Now the above code refactored, to add a model:现在重构上面的代码,添加一个 model:

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();
  }

And finally the model class:最后是 model class:

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

However make sure you upgrade flutter to version 1.13.0.但是请确保将 flutter 升级到版本 1.13.0。 At least for me, I was getting several build errors in lower versions.至少对我来说,我在较低版本中遇到了几个构建错误。

Karee is a set of tools that implementes MVC design in Flutter. Karee 是一套在 Flutter 中实现 MVC 设计的工具。 It help you to manage your Controllers, your routes, your screens and more.它可以帮助您管理控制器、路线、屏幕等。 Refer to karee github wiki to get documentation.请参阅 karee github wiki 以获取文档。

You Can use Karee .您可以使用Karee It supports Flutter 2.XX支持Flutter 2.XX

To installation run npm install -g karee Then karee create After creating a New Flutter project based on Karee you can add new controller要安装运行npm install -g karee然后 karee karee create在基于 Karee 创建一个新的 Flutter 项目后,您可以添加新的 controller

Sample Code示例代码

Creating à New controller创建à新的controller

    Karee generate --controller --path auth Authentication

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

@Controller
class AuthenticationController {

       login(username, password) {

                /// Your custom code

       }
}

Add route添加路线

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

Use in your Screen在您的屏幕中使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM