Flutter MVVM架构插件my_mvvm的使用

Flutter MVVM架构插件my_mvvm的使用

如果你需要一个更简单的状态管理方法,并且希望可以轻松自定义你的状态管理解决方案,那么你可以直接使用这个插件,仅此而已。

示例代码

以下是使用 my_mvvm 插件的基本示例:

import 'package:flutter/material.dart';
import 'package:my_mvvm/my_mvvm.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter my_mvvm_package_example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'my_mvvm package example '),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 使用 ViewModelBuilder 来创建视图模型驱动的界面
    return ViewModelBuilder<CounterViewModel>.reactive(
      builder: (context, viewModel, child) => Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              // 显示当前计数器的值
              Text(
                viewModel.counter.toString(),
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: Row(
          children: [
            const SizedBox(
              width: 50,
            ),
            // 增加计数器按钮
            FloatingActionButton(
              onPressed: viewModel.incrementCounter,
              tooltip: 'Increment',
              child: const Icon(Icons.add),
            ),
            // 减少计数器按钮
            FloatingActionButton(
              onPressed: viewModel.decrementCounter,
              tooltip: 'Decrement',
              backgroundColor: Colors.red,
              child: const Icon(
                Icons.remove,
              ),
            ),
          ],
        ),
      ),
      viewModelBuilder: () => CounterViewModel(),
      onModelReady: (viewModel) => viewModel.setCounterTo999(),
      disposeViewModel: false,
      fireOnModelReadyOnce: true,
    );
  }
}

// 定义我们的视图模型
class CounterViewModel extends BaseViewModel {
  int _counter = 0;

  // 获取当前计数器的值
  int get counter => _counter;

  // 增加计数器的方法
  void incrementCounter() {
    _counter++;
    notifyListeners(); // 通知所有监听者数据已更改
  }

  // 减少计数器的方法
  void decrementCounter() {
    if (_counter != 0) {
      _counter--;
    }
    notifyListeners(); // 通知所有监听者数据已更改
  }

  // 设置计数器为999的方法
  void setCounterTo999() {
    _counter = 999;
    notifyListeners(); // 通知所有监听者数据已更改
  }
}

代码解释

  1. 主应用入口

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

    这里定义了应用的入口点,启动 MyApp 组件。

  2. MyApp 组件

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter my_mvvm_package_example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(title: 'my_mvvm package example '),
        );
      }
    }
    

    MyApp 是应用的根组件,设置了一些基本配置如主题颜色等。

  3. MyHomePage 组件

    class MyHomePage extends StatelessWidget {
      final String title;
      const MyHomePage({Key? key, required this.title}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return ViewModelBuilder<CounterViewModel>.reactive(
          builder: (context, viewModel, child) => Scaffold(
            appBar: AppBar(
              title: Text(title),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  const Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    viewModel.counter.toString(),
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ],
              ),
            ),
            floatingActionButton: Row(
              children: [
                const SizedBox(
                  width: 50,
                ),
                FloatingActionButton(
                  onPressed: viewModel.incrementCounter,
                  tooltip: 'Increment',
                  child: const Icon(Icons.add),
                ),
                FloatingActionButton(
                  onPressed: viewModel.decrementCounter,
                  tooltip: 'Decrement',
                  backgroundColor: Colors.red,
                  child: const Icon(
                    Icons.remove,
                  ),
                ),
              ],
            ),
          ),
          viewModelBuilder: () => CounterViewModel(),
          onModelReady: (viewModel) => viewModel.setCounterTo999(),
          disposeViewModel: false,
          fireOnModelReadyOnce: true,
        );
      }
    }
    

    MyHomePage 是应用的主要页面。这里使用了 ViewModelBuilder 来构建一个依赖于视图模型的界面。视图模型负责管理状态和业务逻辑。

  4. CounterViewModel 类

    class CounterViewModel extends BaseViewModel {
      int _counter = 0;
    
      int get counter => _counter;
    
      void incrementCounter() {
        _counter++;
        notifyListeners();
      }
    
      void decrementCounter() {
        if (_counter != 0) {
          _counter--;
        }
        notifyListeners();
      }
    
      void setCounterTo999() {
        _counter = 999;
        notifyListeners();
      }
    }
    

更多关于Flutter MVVM架构插件my_mvvm的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter MVVM架构插件my_mvvm的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


my_mvvm 是一个用于 Flutter 应用的 MVVM 架构插件,它帮助开发者更容易地实现 Model-View-ViewModel 架构模式。以下是如何使用 my_mvvm 插件的基本步骤和示例代码。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 my_mvvm 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  my_mvvm: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 创建 Model

Model 是应用程序的数据层,通常包含业务逻辑和数据操作。

class UserModel {
  String name;
  int age;

  UserModel({required this.name, required this.age});
}

3. 创建 ViewModel

ViewModel 是 Model 和 View 之间的桥梁,负责处理业务逻辑并将数据暴露给 View。

import 'package:my_mvvm/my_mvvm.dart';

class UserViewModel extends ViewModel {
  UserModel _user;

  UserViewModel(this._user);

  String get name => _user.name;
  int get age => _user.age;

  void updateName(String newName) {
    _user.name = newName;
    notifyListeners();  // 通知 View 更新
  }
}

4. 创建 View

View 是用户界面,负责展示数据和接收用户输入。

import 'package:flutter/material.dart';
import 'package:my_mvvm/my_mvvm.dart';

class UserView extends StatelessWidget {
  final UserViewModel viewModel;

  UserView({required this.viewModel});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('User Profile'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Name: ${viewModel.name}'),
            Text('Age: ${viewModel.age}'),
            ElevatedButton(
              onPressed: () {
                viewModel.updateName('New Name');
              },
              child: Text('Update Name'),
            ),
          ],
        ),
      ),
    );
  }
}

5. 绑定 ViewModel 和 View

main.dart 中,将 ViewModel 和 View 绑定在一起。

import 'package:flutter/material.dart';
import 'package:my_mvvm/my_mvvm.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserView(
        viewModel: UserViewModel(UserModel(name: 'John Doe', age: 30)),
      ),
    );
  }
}
回到顶部