Flutter资源管理插件mobx_resource_bloc的使用

Flutter资源管理插件mobx_resource_bloc的使用

<Bloc + MobX = 资源管理与反应系统结合>

创建可在MobX的反应系统中工作的资源区块。

基础知识

在您的MobX存储中直接使用:

资源区块的主要类ComputedResourceBloc的工作方式类似于MobX中的Computed对象。

资源区块的key将自动更新,每当任何被观察的MobX值发生变化时。该区块的属性,如其statekeyvaluestream也是可观察的值,并且当它们发生变化时会更新任何已订阅的MobX反应。

使用方法

以下是一个完整的示例,展示了如何使用mobx_resource_bloc插件来管理资源并利用MobX的反应系统。

示例代码

import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:mobx_resource_bloc/mobx_resource_bloc.dart';

// 定义一个MobX store
class MyStore with Store {
  final _resourceBloc = ComputedResourceBloc(
    () => fetchUser(),
    key: 'fetch_user',
  );

  @observable
  ObservableFuture<User> userFuture;

  @action
  Future<void> fetchUser() async {
    userFuture = ObservableFuture<User>(() async {
      await Future.delayed(Duration(seconds: 2)); // 模拟网络请求延迟
      return User(name: "Brian Robles", age: 28);
    }());
  }

  @computed
  ComputedResourceBloc<User> get userResourceBloc => _resourceBloc;
}

// 用户模型
class User {
  final String name;
  final int age;

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('MobX Resource Bloc Example')),
        body: StoreProvider<MyStore>(
          create: (_) => MyStore(),
          child: StoreConnector<MyStore, User?>(
            converter: (store) => store.userResourceBloc.value,
            builder: (context, user) {
              if (user == null) {
                return Center(child: CircularProgressIndicator());
              }
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('Name: ${user.name}'),
                    Text('Age: ${user.age}'),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

在这个例子中,我们定义了一个MobX store MyStore,它包含一个ComputedResourceBloc,用于管理从服务器获取用户数据的异步操作。我们还定义了一个简单的User模型来表示用户信息。

MyApp中,我们使用StoreProvider来提供MyStore实例,并通过StoreConnector来连接UI和store。StoreConnector中的converter函数将ComputedResourceBloc<User>转换为User?,并在UI中根据用户数据的状态(加载中或已加载)进行渲染。

功能和问题

此库仍在积极开发中。请自行承担风险使用!


更多关于Flutter资源管理插件mobx_resource_bloc的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter资源管理插件mobx_resource_bloc的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


mobx_resource_bloc 是一个 Flutter 插件,用于结合 MobXBloc 来管理资源。它提供了一种结构化的方式来管理异步资源(如网络请求、数据库查询等),并将它们与 UI 状态管理相结合。

安装

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

dependencies:
  flutter:
    sdk: flutter
  mobx_resource_bloc: ^0.1.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

基本用法

mobx_resource_bloc 的核心概念是 ResourceBloc,它负责管理资源的加载、更新和状态变化。下面是一个简单的示例,展示如何使用 mobx_resource_bloc 来管理一个异步资源。

1. 创建资源类

首先,你需要创建一个资源类,通常是一个 MobXStore。这个类将包含你的业务逻辑和资源状态。

import 'package:mobx/mobx.dart';

part 'my_resource.g.dart';

class MyResource = _MyResource with _$MyResource;

abstract class _MyResource with Store {
  @observable
  String data = '';

  @action
  Future<void> fetchData() async {
    // 模拟异步操作
    await Future.delayed(Duration(seconds: 2));
    data = 'Loaded Data';
  }
}

2. 创建 ResourceBloc

接下来,你需要创建一个 ResourceBloc 来管理这个资源。

import 'package:mobx_resource_bloc/mobx_resource_bloc.dart';

class MyResourceBloc extends ResourceBloc<MyResource> {
  MyResourceBloc() : super(MyResource());

  [@override](/user/override)
  Future<void> loadResource() async {
    await resource.fetchData();
  }
}

3. 在 UI 中使用 ResourceBloc

最后,你可以在 UI 中使用 ResourceBloc 来加载和显示资源。

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

class MyResourcePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => MyResourceBloc(),
      child: Scaffold(
        appBar: AppBar(
          title: Text('My Resource'),
        ),
        body: BlocBuilder<MyResourceBloc, ResourceState>(
          builder: (context, state) {
            if (state.isLoading) {
              return Center(child: CircularProgressIndicator());
            } else if (state.hasError) {
              return Center(child: Text('Error: ${state.error}'));
            } else {
              return Center(child: Text(state.resource.data));
            }
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            context.read<MyResourceBloc>().loadResource();
          },
          child: Icon(Icons.refresh),
        ),
      ),
    );
  }
}
回到顶部