I've new to chaquopy and have been encountering problems since I started. This one is the one that I am facing right now.
To test if my android app can call a python function properly, I've decided to dedicate one of my button into calling a python script and generating a random number that it returns.
My first issue was that it kept on saying "no module named script." I addressed this by placing my script into the android/app/src/python.
Now, what I encounter is AttributeError: module 'script' has no attribute 'mainTextCode'
Here is my code now. The placeholder.py is practically the same code as the python script that I have below.
Future<void> _analyzeImage() async {
// Show loading dialog
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const AlertDialog(
content: Row(
children: [
CircularProgressIndicator(),
SizedBox(width: 20),
Text("Running analysis..."),
],
),
),
);
try {
// Load and execute the Python script
final pythonScript = await rootBundle.loadString('assets/python/placeholder.py');
final result = await Chaquopy.executeCode(pythonScript);
// Close loading dialog
Navigator.pop(context);
// Extract the result
String output = '';
if (result is Map<String, dynamic>) {
output = result['textOutput']?.toString() ?? 'No output';
} else {
output = result?.toString() ?? 'No result';
}
// Show result dialog
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Row(
children: [
Icon(Icons.check_circle, color: Colors.green),
SizedBox(width: 8),
Text('Analysis Result'),
],
),
content: Text(
output,
style: const TextStyle(fontSize: 16),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
} catch (e) {
// Close loading dialog if still open
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
// Show simple error dialog
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Row(
children: [
Icon(Icons.error, color: Colors.red),
SizedBox(width: 8),
Text('Error'),
],
),
content: Text('Failed to run analysis: ${e.toString()}'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('OK'),
),
],
),
);
}
}
Now here is the python code.
import random
def get_random_number():
return random.randint(1, 100)
How can I fix this? Apologies if ever this is a basic problem. I am really new to chaquopy.
Thanks in advance.
It looks like you're using the unofficial Flutter plugin for Chaquopy. In its instructions it says:
Download script.py and put it in python directory. (Kindly note that this python file should not be renamed other than script.py and also if your code doesn't work, check the intendations of the downloaded file.)
"script.py" is a Google Drive link, but there's also a copy of this file in the GitHub repository.