Flutter MVVM实践

目前flutter的弊端使用StatefulWidget导致界面与逻辑无法分离、难以复用。Bloc虽然能解决,但使用StreamController+StreamBuilder太过于麻烦,所以我这边使用了provider进行MVVM模式开发。

1.首先是界面网络请求状态类

enum Status { success, error, loading }

class Resource {
  final Status status;
  final T data;
  final String message;

  const Resource._(this.status, this.data, this.message);

  factory Resource.success(T data) {
    return Resource._(Status.success, data, null);
  }

  factory Resource.error(e, [T data]) {
    var err = (e is DioError && e.error is Exception) ? e.error : e;
    String errMsg;
    try {
      errMsg = err.message;
    } catch (e) {
      errMsg = err.toString();
    }
    return Resource._(Status.error, data, errMsg);
  }

  const Resource.loading([T data]) : this._(Status.loading, data, null);
}

2.ViewModel的基类

mixin ViewModel on ChangeNotifier {
  CancelToken _cancelToken;

  CancelToken get cancelToken => _cancelToken ??= CancelToken();

  BuildContext _context;

  BuildContext get context => _context;

  Resource _resource = Resource.loading();

  Resource get resource => _resource;

  set resource(Resource value) {
    _resource = value;
    notifyListeners();
  }

  void onInit(BuildContext context) {
    _context = context;
  }

  @override
  void dispose() {
    //界面销毁,取消网络请求
    if (_cancelToken?.isCancelled != true) _cancelToken?.cancel();
    super.dispose();
  }
}

3.对provider进行封装,减少代码入侵,优点是不用写BaseState等去继承了,直接使用原本的StatelessWidget、StatefulWidget,尽量使用StatelessWidget

class ViewModelProvider extends StatelessWidget {
  final VM Function(BuildContext context) create;
  final Widget child;
  final Function(BuildContext context, VM vm, Widget child) builder;
  final listen;//true 调用notifyListeners方法后builder方法会刷新,false 不会刷新,配合consumer或selector缩小刷新范围

  const ViewModelProvider({
    Key key,
    @required this.create,
    this.child,
    this.builder,
    this.listen = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider(
      create: (context) => create(context)..onInit(context),
      child: child,
      builder: (context, child) =>
          builder != null ? builder(context, Provider.of(context, listen: listen), child) : null,
    );
  }
}

4.使用方式

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ViewModelProvider(
        create: (context) => MainViewModel(),
        builder: (_, viewModel, child) {
          if (viewModel.resource.status == Status.loading) {
            return Center(child: CircularProgressIndicator());
          }
          if (viewModel.resource.status == Status.error) {
            return Center(child: Text(viewModel.resource.message));
          }
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("姓名:${viewModel.resource?.data?.name} 年龄:${viewModel.resource?.data?.age}"),
              MaterialButton(child: Text("下一页"),onPressed: () => viewModel.onJumpTowPage()),
            ],
          );
        },
      ),
    );
  }
}

//多个网络请求ViewModel范性设置为List
// class MainViewModel with ChangeNotifier, ViewModel{
class MainViewModel with ChangeNotifier, ViewModel {
  @override
  void onInit(BuildContext context) {
    super.onInit(context);
    getUserInfo();
  }

  void getUserInfo() {
    resource = Resource.loading();
    //dio请求,传递cancelToken,页面销毁请求也会销毁
    // Api().getUserInfo(cancelToken:cancelToken)
    //     .then((value) => resource = Resource.success(value))
    //     .catchError((e) => resource = Resource.error(e));
    //模拟请求
    Future.delayed(Duration(seconds: 1), () => UserModel())
        .then((value) => resource = Resource.success(value))
        .catchError((e) => resource = Resource.error(e));
  }

  onJumpTowPage() {
    Navigator.pushNamed(context, "/towPage");
  }

//get方法,多请求方便外层获取数据
// xx1 get xx1=>resource?.data[0];
// xx2 get xx2=>resource?.data[1];
// xx3 get xx3=>resource?.data[3];
//多请求例子
// void multiRequest() {
//   resource = Resource.loading();
//   Future.wait([Api.xx1(), Api.xx2(), Api.xx3()])
//       .then((value) => resource = Resource.success(value))
//       .catchError((e) => resource = Resource.error(e));
// }
}

class UserModel {
  String name = "张三";
  int age = 20;
}

分页界面也可以用,配合Resource的工厂构造传递data。

你可能感兴趣的:(Flutter MVVM实践)