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

如何在Flutter安卓应用中调用Python计算脚本作为计算器?

Integrating Python Math Scripts into a Flutter Calculator App

Absolutely! There are several reliable ways to turn your Python math scripts into a backend for a Flutter calculator. Let’s walk through the most practical methods, from quick-and-easy to more customizable:

1. Use the flutter_python Plugin (Simplest Approach)

This plugin lets you run Python code directly within your Flutter app without needing a separate server. Perfect for lightweight math scripts.

Steps:

  • Add the plugin to your pubspec.yaml:
    dependencies:
      flutter:
        sdk: flutter
      flutter_python: ^0.5.0
    
  • Place your Python script (e.g., calculator.py) in the assets folder of your Flutter project, and declare it in pubspec.yaml:
    assets:
      - assets/calculator.py
    
  • Example Python script (calculator.py):
    def calculate(num1, num2, operation):
        if operation == "add":
            return num1 + num2
        elif operation == "subtract":
            return num1 - num2
        # Add more operations like multiply/divide as needed
    
  • Call the script from Flutter:
    import 'package:flutter_python/flutter_python.dart';
    
    // Initialize the Python interpreter
    final FlutterPython flutterPython = FlutterPython();
    
    // Function to run calculation
    Future<double?> runCalculation(double num1, double num2, String operation) async {
      try {
        // Load the script from assets
        await flutterPython.executeScript('assets/calculator.py');
        // Call the calculate function with inputs
        var result = await flutterPython.executeFunction(
          'calculate',
          [num1, num2, operation],
        );
        return double.parse(result.toString());
      } catch (e) {
        print('Error running Python script: $e');
        return null;
      }
    }
    

2. Wrap Python Scripts in a Local HTTP API (More Flexible)

If your scripts are complex or you want to reuse them across platforms, package them into a lightweight HTTP API (using FastAPI or Flask) and have Flutter call it via HTTP requests.

Steps:

  • Create a FastAPI app for your calculator:
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/calculate")
    def calculate(num1: float, num2: float, operation: str):
        if operation == "add":
            return {"result": num1 + num2}
        elif operation == "subtract":
            return {"result": num1 - num2}
        # Extend with other operations here
    
  • Package the API into a standalone executable using PyInstaller:
    pyinstaller --onefile --name calculator_api main.py
    
  • Ship this executable with your Flutter app (place it in platform-specific assets, e.g., Android's assets or iOS's Resources), then launch it from Flutter when the app starts.
  • Call the API from Flutter using the http package:
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    Future<double?> fetchCalculation(double num1, double num2, String operation) async {
      final response = await http.get(
        Uri.parse('http://localhost:8000/calculate?num1=$num1&num2=$num2&operation=$operation'),
      );
    
      if (response.statusCode == 200) {
        var data = jsonDecode(response.body);
        return data['result'];
      } else {
        print('Request failed with status: ${response.statusCode}');
        return null;
      }
    }
    

3. Use Flutter Platform Channels (Full Customization)

For complete control, use Flutter's Platform Channels to integrate Python directly with native Android/iOS code. This requires platform-specific setup:

Android (Using Chaquopy)

  • Add Chaquopy to your Android project's build.gradle:
    buildscript {
        dependencies {
            classpath "com.chaquo.python:gradle:14.0.2"
        }
    }
    
  • Enable Chaquopy in your app's build.gradle and add your Python script to src/main/python:
    apply plugin: "com.chaquo.python"
    
    android {
        defaultConfig {
            python {
                srcDir "src/main/python"
            }
        }
    }
    
  • Create a Method Channel in Flutter to call the Python function from native Android code.

iOS (Using PythonKit)

  • Add PythonKit via CocoaPods in your Podfile:
    pod 'PythonKit'
    
  • Embed your Python script in the iOS project, then use PythonKit in native Swift code to run the script, and connect it to Flutter via a Method Channel.

Key Notes

  • Always handle errors gracefully (e.g., invalid inputs, script failures) to keep your app stable.
  • For performance-critical calculations, test each approach to see which works best for your use case.
  • If targeting iOS, note that Apple has restrictions on running interpreted code; the flutter_python plugin or PythonKit should still work, but verify with Apple's guidelines.

内容的提问来源于stack exchange,提问作者Admirable Peace

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:09:23