preface

This is the second article in the Dio series, following the basic introduction to Dio and an example of getting tabbed data:

  • Introduction and Combat (xXII) : First meeting, Internet request king of dio

This section describes how to use the DELETE method provided by Dio to connect to the delete interface in the background. Before commissioning, you need to start the background project, refer to the previous article, and run the background application (while preparing the background database data).

Interface interaction

We need to implement the long-press pop-up list element to delete the operation. The interface implementation is not the focus of this article. I went to pub and found a FocusedMenu to implement it. FocusedMenu is easy to implement, we just need to wrap the list elements with FocusedMenuHolder:

// dynamic_item.dart

@override
Widget build(BuildContext context) {
  return FocusedMenuHolder(
    child: Container(
      // Omit the original list element building code
    ),
    onPressed: () {
      // Click the event
      _handlePressed(context);
    },
    // Long press the menu
    menuItems: <FocusedMenuItem>[
      FocusedMenuItem(
          title: Text("View details"),
          trailingIcon: Icon(Icons.remove_red_eye_outlined),
          onPressed: () {
            _handlePressed(context);
          }),
      FocusedMenuItem(
        title: Text("Cancel"),
        trailingIcon: Icon(Icons.cancel),
        onPressed: () {},
      ),
      FocusedMenuItem(
          title: Text(
            "Delete", style: TextStyle(color: Colors.redAccent), ), trailingIcon: Icon( Icons.delete, color: Colors.redAccent, ), onPressed: () { handleDelete(dynamicEntity.id); })],); }Copy the code

The key is to hold down the menu to configure the corresponding menu name, icon, and response event. The handleDelete method here is passed from the list page and receives the ID of a list element to process the delete logic on the list page.

Network request to delete implementation

Add a deletion method to dynamic_service.dart for network request deletion, as shown below:

static Future delete(String id) async {
  var result = await Dio().delete(
    host + 'dynamics/' + id.);

  return result;
}
Copy the code

The method is simple. Just call the Dio instance delete method and concatenate the ID to be deleted with the URL address.

The business code for the corresponding call is as follows, which is called when the delete button of the pop-up menu is clicked. If the method is successfully deleted (status code 200), the element is removed from the current list and the status update interface is refreshed. If it fails (the status code is other), an error message is displayed via SnackBar.

void _onItemDelete(String id) async {
    try {
      var response = await DynamicService.delete(id);
      if (response.statusCode == 200) {
        setState(() {
          _listItems.removeWhere((element) => element.id == id);
        });
      } else {
        _showErrorInfo(this.context, response.statusMessage); }}on DioError catch (e) {
      _showErrorInfo(this.context, e.message);
    } catch (e) {
      _showErrorInfo(this.context, e.toString()); }}Copy the code

First, we use a try… A catch wraps a network request because an exception may occur in the background, such as the data has been deleted, there is a bug in the background, etc. At present, we have not uniformly handled Dio exceptions, so it is necessary to do exception catching in order to prevent application crash caused by background exceptions. We can actually pass a virtual ID validation exception, and we’ll see that Dio will throw a DioError, and we can tell the user the error message.

By the way, you can see that Dart has an on keyword, where you can use multiple ON’s to match different exceptions. The form is as follows, where the second argument to catch is the stack information.

try {
  // ...
} on ExceptionType1 catch (e) {
  // ExceptionType1 Exception handling
} on ExceptionType2 catch (e) {
  // ExceptionType2 Exception handling
} catch (e,s) {
  // Other exception handling
}
Copy the code

Running effect

The running effect is as follows (the second is the case of catching exceptions) :

The source code

Source address: gitee.com/island-code…