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

Flutter波斯语应用数字转波斯数字的解决方案咨询

解决Flutter波斯语应用中数字无法转换为波斯数字的问题

核心原因

字体支持波斯数字仅意味着它能正确渲染波斯数字字符(۰۱۲۳۴۵۶۷۸۹),但用户输入或服务器返回的是阿拉伯数字字符(0123456789),两者编码不同,不会自动转换,需要手动处理字符替换。


1. 通用数字转换工具函数

先实现一个全局可用的转换函数,把阿拉伯数字字符串替换为波斯数字:

String convertToPersianNumber(String input) {
  const englishDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
  const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];

  for (int i = 0; i < englishDigits.length; i++) {
    input = input.replaceAll(englishDigits[i], persianDigits[i]);
  }
  return input;
}

2. TextField输入实时转换

方法一:使用TextInputFormatter(推荐)

自定义输入格式化器,自动将输入的阿拉伯数字转为波斯数字:

class PersianNumberFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: convertToPersianNumber(newValue.text),
      selection: newValue.selection,
    );
  }
}

// TextField中使用
TextField(
  inputFormatters: [PersianNumberFormatter()],
  decoration: const InputDecoration(hintText: '输入数字'),
)

方法二:通过onChanged回调处理

如果需要更灵活的逻辑,可在输入变化时手动更新控制器:

final TextEditingController _controller = TextEditingController();

// ...

TextField(
  controller: _controller,
  onChanged: (value) {
    final converted = convertToPersianNumber(value);
    if (_controller.text != converted) {
      _controller.text = converted;
      // 保持光标在末尾
      _controller.selection = TextSelection.fromPosition(
        TextPosition(offset: converted.length),
      );
    }
  },
)

3. 服务器响应数据转换

在解析服务器返回的JSON时,对数字字段统一转换:

class Product {
  final String id;
  final String name;
  final String price;

  Product({required this.id, required this.name, required this.price});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: convertToPersianNumber(json['id'].toString()),
      name: json['name'],
      price: convertToPersianNumber(json['price'].toString()),
    );
  }
}

4. 系统级本地化配置(可选)

如果需要系统组件(如日期选择器、计数器)也显示波斯数字,需配置应用本地化:

MaterialApp(
  localizationsDelegates: const [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('fa', 'IR'), // 波斯语(伊朗)
  ],
  locale: const Locale('fa', 'IR'),
  home: const YourHomePage(),
)

注意:系统本地化仅影响系统组件的默认数字显示,用户输入和服务器数据仍需手动转换。

内容的提问来源于stack exchange,提问作者yalda mohasseli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:55:09