Home > Mobile >  How to Pass Map From Child to Parent Flutter
How to Pass Map From Child to Parent Flutter

Time:03-20

So, I am taking an example from Flutter documentation. Actually, it is working fine but I just want to customize it by passing the result (Map) to parent

import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      title: 'Returning Data',
      home: HomeScreen(),
    ),
  );
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Map AdList = {};
  callback(AdListNew){
    setState(() {
      AdList = AdListNew; ////// 1. WANT TO UPDATE THE LIST WITH NEW MAP FROM CHILD ////
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Returning Data Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('This text is'),
            SelectionButton(AdList,callback),
          ],
        ),
      ),
    );
  }
}

class SelectionButton extends StatefulWidget {
  Map AdList;
  Function(String) callback;

  SelectionButton(this.AdList,this.callback);
  @override
  State<SelectionButton> createState() => _SelectionButtonState();
}

class _SelectionButtonState extends State<SelectionButton> {
  String show = 'Pick me';
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: (){
        NavigateAndDisplay(context);
      },
      child: Text(show),
    );
  }

  void NavigateAndDisplay(BuildContext context) async{
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const SelectionScreen()),
    );
    // After the Selection Screen returns a result, hide any previous snackbars
    // and show the new result.
    setState(() {
      show = result;
    });
    Map AdListNew = {
      'text':result,
    };
    widget.callback(AdListNew); //// 2. PASS MAP TO PARENT ////
  }
}

Here is an error that I got

lib/main.dart:80:21: Error: The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'String'.

  • 'Map' is from 'dart:core'. widget.callback(AdListNew); ^

I really appreciate any answers. Thank you

CodePudding user response:

You are facing this problem because you declared function with input type as String but you are trying to pass Map, so declaring Function with Map will solve your problem.

Map AdList;
Function(Map) callback;
  • Related