preface
This is the third article of the Dio Network Request, and we will complete the dio learning from shallow to deep. This article describes the form update request, using the patch request to update dynamic data, you need to do the following preparations:
- pull the background new code, project address: background source code, pull to the local, run node seed in the project directory.js generate test data.
- run background application: you can run the background interface application .js the project directory node index, and the default interface address of the project is: http://localhost:3900/api/.
organize your code
review the code of the previous article, and find that the reminder error code of the previous article has nothing to do with the business, and can be extracted as a public method, which is convenient for calling it later in other places, create a new utils/dialogs.dart file, and move the error prompt method inside:
import 'package:flutter/material.dart';
class Dialogs {
static void showInfo(BuildContext context, String info) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(info),
));
}
}
copy the code
previously, we actively refreshed the request data in the method in the list, and actually provided a property itself to set whether to automatically refresh the first time, so we can remove the previous active refresh code and set it to it.initialState
EasyRefresh
firstRefresh
firstRefresh
true
edit the page implementation
First of all, a new file is added, which has three forms and a button, corresponding to the title, content and image link address (here we do not consider image upload for the time being). The form leverages the generic form component that we encapsulated earlier, as you can refer to the previous one: Flutter encapsulating the text input box. Here when no data is requested we display “Loading…”, if the request is successful, the actual form content is displayed, and the code for building the interface is as follows:dynamic_edit.dart
_getFormWidgets() {
if (_formData == null)
return Center(
child: Text('加载中...'),
);
return Container(
child: Column(
children: [
FormUtil.textField(
'title',
_formData['title']['value'] ?? '',
controller: _formData['title']['controller'] ?? null,
hintText: '请输入标题',
prefixIcon: Icons.title,
onChanged: _handleTextFieldChanged,
onClear: _handleClear,
),
FormUtil.textField(
'content',
_formData['content']['value'] ?? '',
controller: _formData['content']['controller'] ?? null,
hintText: '请输入内容',
prefixIcon: Icons.content_paste,
onChanged: _handleTextFieldChanged,
onClear: _handleClear,
),
FormUtil.textField(
'imageUrl',
_formData['imageUrl']['value'] ?? '',
controller: _formData['imageUrl']['controller'] ?? null,
hintText: '请输入图片链接',
prefixIcon: Icons.image,
onChanged: _handleTextFieldChanged,
onClear: _handleClear,
),
ButtonUtil.primaryTextButton('保存', () {
_handleSubmit();
}, context),
],
),
);
}
copy the code
in the long-press bullet layer of the list item, we added an edit button, click and jump to the editing page, specifically refer to the source code.
get detailed data
Before editing, we want to fill the form with id request background data, here using the get request we talked about earlier, as follows. If the request is successful, when status code 200 is returned, the _formData data for the build form, which is the data required by the form, and updates the interface. If the request fails, the encapsulated infotip method is called, displaying an error message.
void _getDynamic(String id) async {
try {
var response = await DynamicService.get(id);
if (response.statusCode == 200) {
dynamicEntity = DynamicEntity.fromJson(response.data);
setState(() {
_formData = {
'title': {
'value': dynamicEntity.title,
'controller': TextEditingController(text: dynamicEntity.title),
'obsecure': false,
},
'content': {
'value': dynamicEntity.content,
'controller': TextEditingController(text: dynamicEntity.content),
'obsecure': false,
},
'imageUrl': {
'value': dynamicEntity.imageUrl,
'controller': TextEditingController(text: dynamicEntity.imageUrl),
'obsecure': false,
},
};
});
} else {
Dialogs.showInfo(this.context, response.statusMessage);
}
} on DioError catch (e) {
Dialogs.showInfo(this.context, e.message);
} catch (e) {
Dialogs.showInfo(this.context, e.toString());
}
}
copy the code
submit the update data
Before submitting the data, we need to do the verification, here for the sake of simplicity, just to ensure that the data is not empty, and then we can check the tool to accurately check each field. After the validation passes, extract the actual form data to be submitted from the _fromData.
_handleSubmit() async {
if ((_formData['title']['value'] as String).trim() == '') {
Dialogs.showInfo(this.context, '标题不能为空');
return;
}
if ((_formData['content']['value'] as String).trim() == '') {
Dialogs.showInfo(this.context, '内容不能为空');
return;
}
if ((_formData['imageUrl']['value'] as String).trim() == '') {
Dialogs.showInfo(this.context, '图片链接不能为空');
return;
}
try {
Map<String, String> newFormData = {};
_formData.forEach((key, value) {
newFormData[key] = value['value'];
});
var response = await DynamicService.update(dynamicEntity.id, newFormData);
if (response.statusCode == 200) {
Dialogs.showInfo(context, '保存成功');
} else {
Dialogs.showInfo(this.context, response.statusMessage);
}
} on DioError catch (e) {
Dialogs.showInfo(this.context, e.message);
} catch (e) {
Dialogs.showInfo(this.context, e.toString());
}
}
copy the code
in fact, it can be found that our network request in addition to the request method is different, the other code is almost the same, which is why the later chapters need to be uniformly encapsulated, or too many duplicate code, in case one day it will be very painful to change. receiving the id of the data to be updated and the form data to be updated is actually a simple method called.DynamicService.update
Dio
patch
static Future update(String id, Map<String, dynamic> data) async {
var result = await Dio().patch(host + 'dynamics/' + id, data: data);
return result;
}
copy the code
run the effect
after editing, we refresh the data again, and we can see that the content and pictures have changed (how to automatically synchronize the list after saving successfully, we will solve it together after adding it).

summary
This article describes the acquisition of detailed data and the partial modification of entity objects to display Dio’s patch request. As you can see, Dio provides a series of Restful requests in much the same way, leaving room for unified encapsulation. In the next article, we describe how to create data and how to synchronize the updated data to the list after the operation is successful, and the source code address of the network-related code is: Flutter Entry and Actual Network-related Source Code.