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

Flutter中TensorFlow Lite运行报错,如何解决LateInitializationError?

问题解决方法

1. 预测结果显示Instance of 'Future<String>'

这是因为调用predictCharacter时未使用await,直接打印了Future对象。

  • 必须在异步函数内调用predictCharacter,并通过await获取实际结果:
// 示例调用(需在async函数中执行)
void _fetchPrediction() async {
  String result = await predictCharacter(X_test_custom.cast<int>());
  print('Predicted Character: $result');
}

2. LateInitializationError: Field '_sendPort' has not been initialized

该错误由模型输入输出不匹配、未等待IsolateInterpreter初始化完成导致,修复步骤如下:

  • 修正输出缓冲区长度:你的characters列表有16个元素,说明模型是16分类任务,输出应为16维数组,而非1维:
    // 替换原输出缓冲区创建代码
    var outputBuffer = List<double>.filled(16, 0.0);
    
  • 正确获取预测索引:多分类任务需取输出数组中概率最大值对应的索引,而非直接取第一个元素:
    // 替换原predictedIndex逻辑
    double maxProb = outputBuffer[0];
    int predictedIndex = 0;
    for (int i = 1; i < outputBuffer.length; i++) {
      if (outputBuffer[i] > maxProb) {
        maxProb = outputBuffer[i];
        predictedIndex = i;
      }
    }
    
  • 等待IsolateInterpreter.run执行完成:run方法是异步的,必须加await避免未初始化就访问内部资源:
    await isolateInterpreter.run(inputBuffer, outputBuffer);
    
  • 优化模型加载逻辑:避免每次预测重复加载模型,将模型实例缓存到类成员变量:
    // 修改loadModel函数,赋值给类成员interpreter
    Future<void> loadModel() async {
      try {
        interpreter = await Interpreter.fromAsset('assets/myPersonalityModel.tflite');
        print('Model loaded');
      } catch (e) {
        print('Error: $e');
      }
    }
    
    // 修改predictCharacter,优先使用已加载的模型
    Future<String> predictCharacter(List<int> inputData) async {
      try {
        if (interpreter == null) {
          await loadModel();
          if (interpreter == null) return 'Model not loaded';
        }
    
        final isolateInterpreter = await IsolateInterpreter.create(address: interpreter!.address);
        // ... 其余代码保持不变
      } catch (e) {
        print('Error: $e');
        return "Prediction failed";
      }
    }
    

额外优化

  • 调用predictCharacter时将X_test_custom转为List<int>:X_test_custom.cast<int>()
  • 在页面销毁时关闭模型释放资源:
    @override
    void dispose() {
      interpreter?.close();
      super.dispose();
    }
    

内容的提问来源于stack exchange,提问作者Munkhtsetseg G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:37:08