I've started working on a project with Flutter and Dart. The app should display a spectrometer based on the signal received by the microphone. I used flutter_fft to handle the signals and syncfusion to make the chart.
While coding the startListening() function i've stumbled across this weird error:
The argument type 'String' can't be assigned to the parameter type 'int'. How can I resolve this error? 'freq' or 'frequency? should be the keys to extract the audio. I tried everything, even if I am an absolute beginner in Android coding, but neither AI seems to know the answer.
this is the whole code:
import 'package:flutter/material.dart';
import 'package:flutter_fft/flutter_fft.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class Spettrometro extends StatefulWidget {
@override
_SpettrometroState createState() => _SpettrometroState();
}
class _SpettrometroState extends State<Spettrometro> {
FlutterFft flutterFft = FlutterFft();
List<DataPoint> data = [];
bool isRecording = false;
@override
void initState() {
super.initState();
requestPermission();
}
Future<void> requestPermission() async {
var status = await Permission.microphone.request();
if (status.isGranted) {
startListening();
} else {
print("Permesso microfono negato");
}
}
void startListening() async {
await flutterFft.startRecorder();
setState(() => isRecording = true);
flutterFft.onRecorderStateChanged.listen((event) {
final dynamic frequencyValue = event['freq']; // This is the problematic line of code
double? freq;
// Conversione robusta a double
if (frequencyValue != null) {
freq = double.tryParse(frequencyValue.toString());
}
if (freq != null && freq > 0) {
setState(() {
data.add(DataPoint(DateTime.now(), freq!));
if (data.length > 100) data.removeAt(0);
});
}
});
}
void stopListening() {
flutterFft.stopRecorder();
setState(() => isRecording = false);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Spettrometro Audio")),
body: Column(
children: [
Expanded(
child: SfCartesianChart(
primaryXAxis: DateTimeAxis(),
primaryYAxis: NumericAxis(
numberFormat:
NumberFormat.decimalPattern(),
),
series: <LineSeries<DataPoint, DateTime>>[
LineSeries<DataPoint, DateTime>(
dataSource: data,
xValueMapper: (DataPoint point, _) => point.time,
yValueMapper: (DataPoint point, _) => point.frequency,
),
],
),
),
ElevatedButton(
onPressed: isRecording ? stopListening : startListening,
child: Text(isRecording ? "Ferma" : "Avvia"),
),
],
),
);
}
}
class DataPoint {
final DateTime time;
final double frequency;
DataPoint(this.time, this.frequency);
}
I tried to force that line of code using
double? freq = event["freq"] is num ? (event["freq"] as num).toDouble() : double.tryParse(event["freq"].toString());
but it doesn't work