You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Flutter向Flask服务端发送Unicode字符并解决相关报错

解决方案

你遇到的报错和Unicode编码本身无关,是三处逻辑错误导致的,按以下步骤修改即可正常传输希伯来语等Unicode字符:

1. 修复文件写入报错(对应io.UnsupportedOperation: not writable)

你调用open('data.csv')时默认使用只读模式,没有写入权限,同时需要指定UTF-8编码保证Unicode字符正常存储,修正后的scripts.add代码:

import csv

def add(w1, w2):
    # a+为追加写入模式,指定encoding=utf-8兼容所有Unicode字符,newline=''避免csv生成多余空行
    with open('data.csv', 'a+', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([w1, w2])

注:with语法会自动关闭文件,不需要手动调用f.close

2. 修复Flask参数接收逻辑

你使用POST请求发送JSON格式的请求体,不能用request.args(只能获取URL拼接的查询参数)获取参数,修正后的接口代码:

from flask import request, jsonify

# 声明接口接受POST请求
@app.route('/add', methods=['POST'])
def add():
    # 从JSON请求体中读取参数
    req_data = request.get_json()
    english_word = req_data.get("english")
    hebrew_word = req_data.get("hebrew")
    scripts.add(english_word, hebrew_word)
    # 返回正常响应给前端
    return jsonify({"code": 0, "msg": "success"}), 200

3. 修复Flutter端发送逻辑

不需要手动对希伯来语文本做UTF-8编码,JSON序列化本身支持Unicode字符,同时需要添加JSON格式的请求头,修正后的代码:

() async{
      Map<String, String> body = {'english': englishController.text, 'hebrew': hebrewController.text};
      String jsonString = json.encode(body);

      var response = await http.post(
        Uri.parse("http://192.168.80.46:8080/add"),
        headers: {"Content-Type": "application/json; charset=utf-8"},
        body: jsonString,
        encoding: Encoding.getByName('UTF-8')
      );
      if(response.statusCode == 200){
        showSnackBar("Succesfully added new pair of words");
      }else{
        showSnackBar("Something went wrong...");
      }
      Navigator.of(context).pop();
    }

内容的提问来源于stack exchange,提问作者Efim Rubin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:15:09