Flutter结果展示插件fluent_result的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter结果展示插件fluent_result的使用

fluent_result 是一个轻量级的Dart库,旨在解决常见的操作成功或失败的问题。它通过返回表示操作成功或失败的对象来替代抛出异常或使用异常处理。

使用方法

创建 Result

成功的结果

Result result = Result.success();
Result sameResult = Result.ok;
Result sameResult2 = success();

失败的结果

Result errorResult1 = Result.failWith('a fail reason');
Result errorResult2 = Result.failWith(ResultError('my error message'));
Result errorResult3 = Result.failWith(MyException('exception description'));
Result errorResult4 = Result.failWith(['a fail reason', ResultError('my error message')]);

Result same = fail(MyException('exception description'));

泛型 ResultOf<T>

带有值的成功结果

ResultOf<MyObject> result = ResultOf.success(MyObject());
ResultOf<MyObject> sameResult = successWith(MyObject());
MyObject value = result.value;

带有错误且无值的失败结果

ResultOf<MyObject> result = ResultOf.failWith<MyObject>(ResultError('a fail reason'));
MyObject value = result.value; // is null because of the fail result

failIf()okIf()

final result1 = Result.failIf(() => firstName.isEmpty, "First Name is empty");
final result2 = Result.okIf(() => firstName.isNotEmpty, 'First name should not be empty');

trySynctryAsync

同步

final res = Result.trySync(() {
  throw 'Some exception';
});

res.isFail.should.beTrue();
res.errorMessage.should.be('Some exception');

异步

final res = await Result.tryAsync(() async {
  await Future.delayed(const Duration(seconds: 2));
  print('Done');
});

res.isSuccess.should.beTrue();

fold

Result res = fail('error reason');
res.fold(
  onFail: (errors) {
    // process errors
  },
  onSuccess: () {
    // process success path
  },
);

ResultOf<String> resultWithData = successWith('someData');
resultWithData.foldWithValue(
  onFail: (errors) {
    // process errors
  },
  onSuccess: (data) {
    // process success path with data
  },
);

转换 Result

成功结果转换

final anotherResult =
    result.map((customer) => User(customer.id));

失败结果转换

final anotherResult = failResult.map<Customer>();

自定义错误

class InvalidPasswordError extends ResultError {
  const InvalidPasswordError(String message)
      : super(message);
}

class CustomerNotFound extends ResultError {
  const CustomerNotFound({
    required this.customerId,
  }) : super('Customer not found with ID $customerId');

  final int customerId;

  @override
  String toString() => message;
}

收集错误

final err1 = CustomerNotFound(customerId: 1);
final res = Result.fail(err1);

final err2 = InvalidPasswordError('The password 123456 is invalid');
res.add(err2);

res.contains<InvalidPasswordError>(); // true
res.get<InvalidPasswordError>().should.not.beNull();

异常处理器匹配器

ResultConfig.exceptionHandlerMatchers = {
  DioError: (e) {
    print('🟠 DIO FAIL RESULT: $e');
    final failure = ResultOf.failWith(DioErrorResult(e as DioError));
    return failure;
  },
};

示例代码

以下是一个完整的示例代码,展示了如何在Flutter项目中使用 fluent_result 插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Fluent Result Example')),
        body: Center(child: MyWidget()),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String resultMessage = '';

  void _simulateOperation() {
    // 模拟操作
    final result = Result.trySync(() {
      if (DateTime.now().second % 2 == 0) {
        throw Exception('偶数秒发生错误');
      } else {
        return '操作成功';
      }
    });

    setState(() {
      if (result.isSuccess) {
        resultMessage = '操作成功: ${result.value}';
      } else {
        resultMessage = '操作失败: ${result.errorMessage}';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(resultMessage),
        ElevatedButton(
          onPressed: _simulateOperation,
          child: Text('执行操作'),
        ),
      ],
    );
  }
}

这个示例代码展示了如何在Flutter应用中使用 fluent_result 来处理同步操作的结果,并根据结果更新UI。你可以根据需要扩展此示例以适应异步操作或其他复杂场景。


更多关于Flutter结果展示插件fluent_result的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter结果展示插件fluent_result的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用fluent_result插件来展示结果的示例代码。fluent_result是一个Flutter包,用于以美观和直观的方式展示操作结果,比如成功、警告、错误等。

首先,确保你已经在pubspec.yaml文件中添加了fluent_result依赖:

dependencies:
  flutter:
    sdk: flutter
  fluent_result: ^latest_version  # 请替换为最新版本号

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

接下来,你可以在你的Flutter应用中使用FluentResult组件。以下是一个完整的示例,展示了如何使用FluentResult来显示成功、警告和错误消息。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fluent Result Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ResultScreen(),
    );
  }
}

class ResultScreen extends StatefulWidget {
  @override
  _ResultScreenState createState() => _ResultScreenState();
}

class _ResultScreenState extends State<ResultScreen> {
  void showSuccess() {
    FluentResult.show(
      context: context,
      result: Result.success(
        title: 'Success',
        message: 'Operation completed successfully!',
      ),
      actions: [
        ResultAction(
          label: 'OK',
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }

  void showWarning() {
    FluentResult.show(
      context: context,
      result: Result.warning(
        title: 'Warning',
        message: 'This is a warning message.',
      ),
      actions: [
        ResultAction(
          label: 'OK',
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }

  void showError() {
    FluentResult.show(
      context: context,
      result: Result.error(
        title: 'Error',
        message: 'An error occurred. Please try again.',
      ),
      actions: [
        ResultAction(
          label: 'Retry',
          onPressed: () {
            // Handle retry logic here
            Navigator.pop(context);
          },
        ),
        ResultAction(
          label: 'Cancel',
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fluent Result Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: showSuccess,
              child: Text('Show Success'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: showWarning,
              child: Text('Show Warning'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: showError,
              child: Text('Show Error'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们定义了一个ResultScreen,它包含三个按钮,分别用于显示成功、警告和错误消息。点击每个按钮时,会调用相应的showSuccessshowWarningshowError方法,这些方法使用FluentResult.show方法来显示结果。

每个结果包含标题、消息和一组操作按钮。当用户点击操作按钮时,可以执行相应的逻辑(例如关闭结果对话框)。

你可以根据需要自定义结果对话框的样式和行为。fluent_result插件提供了丰富的配置选项,以满足不同的使用场景。

回到顶部