get_command

pub package

This library helps providing feedback to the user while executing a controller function. It is intended to be used with the Get library.

Let's create an example to showcase the usage:

  1. Create a controller with an async function 'longRunningTask':
import 'package:get/get.dart';

class HomeController extends GetxController {
  final count = 0.obs;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}

  Future<void> longRunningTask() async {
    await Future.delayed(Duration(seconds: 1));
    count.value++;
  }
}

  1. Create a simple view
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HomeView'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(() {
              return Text("Current value: ${controller.count}");
            }),
            ElevatedButton(
                child: const Text("Start long running task"),
                onPressed: controller.longRunningTask),
          ],
        ),
      ),
    );
  }
}

The problem with this code is that use can tap the button while it is currently been executed.

Let's extend the controller to use a Command:

code

and update the view to use the Command:

code

In this way the button is displayed as disabled during execution and also displays a little animation. A Command is a callable you can simply use:

code

instead of

code

In the case your controller function throws an exception, it will be catched and the errorMessage property has a value of catchedException.toString().

If you catch any exception within your controller function, you can provide the error message via

code

Rember to call the dispose() function to release any associated resource: That are subscriptions to the state property and the commandFunc and errorMessageProviderFunc will be set to null.

I Hope that Command class is of any help for you.

Libraries

get_command