1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] FlutterMethodChannel Data Passing Issue

Discussão em 'Mobile' iniciado por Stack, Outubro 15, 2024 às 10:53.

  1. Stack

    Stack Membro Participativo

    Hi all this is how I used to render the flutter content in my iOS Application. unfortunately data is not getting send through the FlutterMethodChannel.

    class HeatmapVC: UIViewController {

    lazy var flutterEngine = FlutterEngine(name: "heatmap_engine")
    var methodChannel: FlutterMethodChannel?
    var flutterViewController: FlutterViewController?

    @IBOutlet var heatmapView: UIView!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Run the engine and register plugins
    flutterEngine.run()
    GeneratedPluginRegistrant.register(with: flutterEngine) // Register plugins here

    flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)

    // Add FlutterViewController as a child view controller
    if let flutterVC = flutterViewController {
    addChild(flutterVC)
    flutterVC.view.frame = heatmapView.bounds
    flutterVC.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    heatmapView.addSubview(flutterVC.view)
    flutterVC.didMove(toParent: self)

    // Set up the method channel after the view controller is added
    methodChannel = FlutterMethodChannel(name: "com.b.heatmap/data", binaryMessenger: flutterVC.binaryMessenger)

    // Send data to Flutter
    self.sendDataToFlutter()
    }
    }

    func sendDataToFlutter() {
    let dataToSend: [[String: Any]] = [
    ["country": "India", "socialMedia": "Facebook", "usersInMillions": 25.4],
    ["country": "USA", "socialMedia": "Instagram", "usersInMillions": 19.11],
    ["country": "Japan", "socialMedia": "Facebook", "usersInMillions": 13.3],
    ["country": "Germany", "socialMedia": "Instagram", "usersInMillions": 10.65],
    ["country": "France", "socialMedia": "Twitter", "usersInMillions": 7.54],
    ["country": "UK", "socialMedia": "Instagram", "usersInMillions": 4.93]
    ]

    methodChannel?.invokeMethod("sendData", arguments: dataToSend) { (result: Any?) in
    if let response = result as? String {

    print("Flutter Response: \(response)")
    }
    }
    }



    Below is the error I'm facing.


    [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method sendData on channel com.b.heatmap/data) #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:332:7) #1 _SocialMediaUsersTreemapState._fetchDataFromNative (package:heatmap_b/main.dart:45:36)

    Looking for a solution.

    Below is the flutter code I have used.

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart'; // For MethodChannel
    import 'package:syncfusion_flutter_treemap/treemap.dart';

    void main() => runApp(const MyApp());

    class MyApp extends StatelessWidget {
    const MyApp({super.key});

    @override
    Widget build(BuildContext context) {
    return const MaterialApp(
    home: SocialMediaUsersTreemap(),
    );
    }
    }

    class SocialMediaUsersTreemap extends StatefulWidget {
    const SocialMediaUsersTreemap({super.key});

    @override
    // ignore: library_private_types_in_public_api
    _SocialMediaUsersTreemapState createState() => _SocialMediaUsersTreemapState();
    }

    class _SocialMediaUsersTreemapState extends State<SocialMediaUsersTreemap> {
    static const platform = MethodChannel('com.b.heatmap/data');
    late List<SocialMediaUsers> _source;
    bool _isLoading = true; // To manage loading state

    @override
    void initState() {
    super.initState();

    // Initialize with an empty list until data is received
    _source = <SocialMediaUsers>[];

    // Fetch data from native side
    _fetchDataFromNative();
    }

    Future<void> _fetchDataFromNative() async {
    try {
    // Call the method and await the response
    final List<dynamic> result = await platform.invokeMethod('sendData');

    // Debugging to see if data is received
    print("Data received from native: $result");

    // Process the received data and map it to the SocialMediaUsers list
    setState(() {
    _source = result.map((item) {
    return SocialMediaUsers(
    item['country'],
    item['socialMedia'],
    item['usersInMillions'].toDouble(),
    );
    }).toList();
    _isLoading = false; // Data is loaded
    });
    } on PlatformException catch (e) {
    print("Failed to receive data: '${e.message}'.");
    setState(() {
    _isLoading = false; // End loading even on error
    });
    }
    }

    @override
    Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(title: const Text('Social Media Users Treemap')),
    body: _isLoading
    ? const Center(child: CircularProgressIndicator()) // Show loading spinner
    : _source.isNotEmpty
    ? SfTreemap(
    dataCount: _source.length,
    weightValueMapper: (int index) {
    return _source[index].usersInMillions;
    },
    levels: [
    TreemapLevel(
    groupMapper: (int index) {
    return _source[index].country;
    },
    color: Colors.blueAccent,
    padding: const EdgeInsets.all(2),
    labelBuilder: (BuildContext context, TreemapTile tile) {
    return Padding(
    padding: const EdgeInsets.all(2.0),
    child: Text(
    '${tile.group}\n(${tile.weight.toStringAsFixed(2)}M)',
    style: const TextStyle(color: Colors.white),
    textAlign: TextAlign.center,
    ),
    );
    },
    ),
    ],
    )
    : const Center(
    child: Text('No data available'), // Show if no data is received
    ),
    );
    }
    }

    class SocialMediaUsers {
    const SocialMediaUsers(this.country, this.socialMedia, this.usersInMillions);

    final String country;
    final String socialMedia;
    final double usersInMillions;
    }

    Continue reading...

Compartilhe esta Página