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

a2mppw5e  于 2023-07-31  发布在  Flutter
关注(0)|答案(3)|浏览(165)

我正尝试使用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';
    });
  }
}

字符串

kgqe7b3p

kgqe7b3p1#

使用Greg佩里的优秀库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版。至少对我来说,我在较低版本中遇到了几个构建错误。

nwo49xxi

nwo49xxi2#

Karee是一套在Flutter中实现MVC设计的工具。它可以帮助您管理您的控制器,您的路线,您的屏幕等。参考karee github wiki获取文档。
可以使用Karee。支持Flutter 2.X.X
要安装运行npm install -g karee然后karee create在基于Karee创建一个新的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]);

mgdq6dx1

mgdq6dx13#

flutter 3.10.6 +版本型号/counter_model.dart

class CounterModel {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
  }

  void decrement() {
    _count--;
  }
}

字符串
controllers/counter_controller.dart

import '../models/counter_model.dart';

class CounterController {
  CounterModel model = CounterModel();

  int get count => model.count;

  void increment() {
    model.increment();
  }

  void decrement() {
    model.decrement();
  }
}


views/counter_view.dart

import 'package:flutter/material.dart';
import '../controllers/counter_controller.dart';

class CounterView extends StatefulWidget {
  const CounterView({super.key});

  @override
  State<CounterView> createState() => _CounterViewState();
}

class _CounterViewState extends State<CounterView> {
  final CounterController _controller = CounterController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'Count:',
              style: TextStyle(fontSize: 24.0),
            ),
            Text(
              '${_controller.count}',
              style:
                  const TextStyle(fontSize: 48.0, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () {
                    _controller.increment();
                    setState(() {});
                  },
                  child: const Icon(Icons.add),
                ),
                const SizedBox(width: 16.0),
                ElevatedButton(
                  onPressed: () {
                    _controller.decrement();
                    setState(() {});
                  },
                  child: const Icon(Icons.remove),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}


在一个改变在主。dart

import 'package:flutter/material.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
          return MaterialApp(
           title: 'Counter App',
           theme: ThemeData(
              useMaterial3: true,
              colorScheme: ColorScheme(
                primary: Colors.orange,
                secondary: Colors.amber,
                background: Colors.white,
                surface: Colors.white,
                brightness: Brightness.light,
                error: Colors.red[900]!,
                onPrimary: Colors.white,
                onSecondary: Colors.white,
                onBackground: Colors.black,
                onSurface: Colors.black,
                onError: Colors.white,
              ),
            ),
           home: CounterView(),
          );
  }
}


完整的博客是https://medium.com/@raviyatechnical/flutter-state-management-mvc-pattern-example-for-building-a-counter-app-4a43aa6a1e6

相关问题