Flutter中如何根据下拉选项条件向服务器POST数据
Flutter 多条件构造POST请求体实现方案
核心思路
根据选中的transcript_value选项,动态构造请求体:
- 选中1时,请求体只包含
transcript_value: "VALUE TRANSCRIPTS",不携带SEMESTER参数 - 选中2时,请求体包含
transcript_value: "KHS",同时带上下拉选择的SEMESTER参数
步骤实现
1. 定义状态变量
在StatefulWidget的状态类中,定义两个变量存储用户选择:
int? selectedTranscriptValue; // 存储选中的1/2 String? selectedSemester; // 存储选中的学期值
2. 动态构造请求体
写一个方法根据当前选中状态生成符合要求的请求体:
Map<String, dynamic> buildRequestBody() { final requestBody = <String, dynamic>{}; if (selectedTranscriptValue == 1) { requestBody['transcript_value'] = 'VALUE TRANSCRIPTS'; } else if (selectedTranscriptValue == 2) { requestBody['transcript_value'] = 'KHS'; if (selectedSemester != null) { requestBody['SEMESTER'] = selectedSemester; } } return requestBody; }
3. 发送POST请求
以http包为例,实现请求发送逻辑,同时加入参数合法性校验:
import 'package:http/http.dart' as http; import 'dart:convert'; // 如果API要求JSON格式,需要导入这个 Future<void> submitRequest() async { // 先校验参数:选KHS时必须选学期 if (selectedTranscriptValue == 2 && selectedSemester == null) { // 这里可以用Toast/Alert提示用户选择学期 print('请先选择学期'); return; } final apiUrl = Uri.parse('你的API接口地址'); final requestBody = buildRequestBody(); try { final response = await http.post( apiUrl, // 根据API要求选择编码方式: // 若为form表单格式,直接传body: requestBody // 若为JSON格式,用jsonEncode转换: body: jsonEncode(requestBody), headers: { 'Content-Type': 'application/json', // 对应JSON格式,form格式则用application/x-www-form-urlencoded // 其他必要headers比如token等 }, ); if (response.statusCode == 200) { // 请求成功,处理返回数据 print('请求成功:${response.body}'); } else { // 请求失败,处理错误 print('请求失败,状态码:${response.statusCode},错误信息:${response.body}'); } } catch (e) { // 捕获网络异常 print('网络请求出错:$e'); } }
4. 界面交互关联
将单选按钮、下拉框与状态变量绑定,更新状态:
// 单选按钮组 Row( children: [ Radio( value: 1, groupValue: selectedTranscriptValue, onChanged: (val) { setState(() { selectedTranscriptValue = val as int; selectedSemester = null; // 切换到VALUE TRANSCRIPTS时清空学期选择 }); }, ), const Text('VALUE TRANSCRIPTS'), Radio( value: 2, groupValue: selectedTranscriptValue, onChanged: (val) { setState(() { selectedTranscriptValue = val as int; }); }, ), const Text('KHS'), ], ), // 学期下拉框:仅选中KHS时显示 if (selectedTranscriptValue == 2) DropdownButton<String>( value: selectedSemester, hint: const Text('选择学期'), items: const [ DropdownMenuItem(value: '1', child: Text('第一学期')), DropdownMenuItem(value: '2', child: Text('第二学期')), // 补充其他学期选项 ], onChanged: (val) { setState(() { selectedSemester = val; }); }, ), // 提交按钮:参数合法时才可用 ElevatedButton( onPressed: (selectedTranscriptValue == null) ? null : (selectedTranscriptValue == 2 && selectedSemester == null ? null : submitRequest), child: const Text('提交'), ),
注意事项
- 务必匹配API要求的请求格式(form表单/JSON),否则会导致请求失败
- 可以根据项目状态管理方案(如Provider、Riverpod)替换StatefulWidget的状态管理方式
- 建议加入加载状态和错误提示,提升用户体验
内容的提问来源于stack exchange,提问作者Meikisihka
相关产品推荐
相关产品推荐

