android - Flutter_fft: Why is the argument type 'String' can't be assigned to the parameter type &#3

I've started working on a project with Flutter and Dart. The app should display a spectrometer bas

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

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

Share Improve this question asked Mar 6 at 18:59 KF_2677KF_2677 214 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 1

I managed to fix the problem by forcing the variable to be an integer:

final dynamic frequencyValue = event[0];
double? freq;
int? intValue = int.tryParse(event[1].toString());

For some reason, it now works as intended.

You are trying to get a value from event as if it is a Map<String, dynamic> on this listener:

flutterFft.onRecorderStateChanged.listen((event)...

Update: based on documentation, event is a List<Object> so you need to get it by index and cast it to double. From the docs you can see frequency data is supposed to be on index 1. So yours would be:

frequency = event[1] as double;

See example on https://pub.dev/documentation/flutter_fft/latest/

Original comment:

Are you sure event is a Map? Maybe it's a List? Or maybe it is a Map, but not a Map<String, dynamic>

I'm not familiar with flutter fft, but I imagine their API docs will have some info for you.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744955466a4603166.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信