androidflutterdartflutter-method-channel

How to pass method into another class in flutter


I tried to create a task app using flutter, So I created a text field in DialogBox and my aim is when I add some text into the text field and when I clicked the OK button, I need to show that text in the list. but I have no idea how to call a method in another class, I've added my two classes.

ListTask Class

import 'package:flutter/material.dart';

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

  @override
  State<ListTask> createState() => _ListTaskState();
}

class _ListTaskState extends State<ListTask> {
  final List<String> tasks = ['masu', 'adasf', 'wfqf', 'santha'];

    final TextEditingController _textFieldController = TextEditingController();

  void addItemToList() {
    setState(() {
      tasks.insert(0, _textFieldController.text);
    });
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      height: 320,
      width: double.maxFinite,
      child: ListView.builder(
        padding: EdgeInsets.only(bottom: 10),
        itemCount: tasks.length,
        itemBuilder: (context, index) {
          return Card(
            elevation: 1,
            color: Colors.grey[200],
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ExpansionTile(title: Text(tasks[index]), children: <Widget>[
                  ListTile(
                    title: Text(tasks[index]),
                  )
                ]),
              ],
            ),
          );
        },
      ),
    );
  }

    Future<void> _displayTextInputDialog(BuildContext context) async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('TextField in Dialog'),
            content: TextField(
              onChanged: (value) {
                setState(() {
                  // valueText = value;
                });
              },
              controller: _textFieldController,
              decoration: InputDecoration(hintText: "Text Field in Dialog"),
            ),
            actions: <Widget>[
              FlatButton(
                color: Colors.red,
                textColor: Colors.white,
                child: Text('CANCEL'),
                onPressed: () {
                  setState(() {
                    Navigator.pop(context);
                  });
                },
              ),
              FlatButton(
                color: Colors.green,
                textColor: Colors.white,
                child: Text('OK'),
                onPressed: () {
                  setState(() {
                    addItemToList();
                    Navigator.pop(context);
                  });
                },
              ),
            ],
          );
        });
  }
}

TaskApp Class

import 'package:flutter/material.dart';
import 'package:task_app/Widgets/listtasks.dart';
import 'package:task_app/Widgets/logo.dart';
import 'package:task_app/Widgets/searchbar.dart';

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

  @override
  State<TaskApp> createState() => _TaskAppState();
}

class _TaskAppState extends State<TaskApp> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 10),
            Logo(),
            SizedBox(height: 0),
            SearchBar(),
            SizedBox(height: 15),
            Column(
              children: [
                Text(
                  'All tasks',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0),
                )
              ],
            ),
            SizedBox(height: 15),
            ListTask(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          _displayTextInputDialog(context);
        },
        label: const Text('Add Task'),
        icon: const Icon(Icons.add),
        backgroundColor: Colors.blue[900],
      ),
    );
  }
}

Calling point of that method in TaskApp Class:

Calling point of that method in TaskApp Class

Method:

Method


Solution

  • You can give this a try, it will call a method defined in ListTask(StatefulWidget) from TaskApp(StatefulWidget) widget.

    TaskApp.dart

    import 'package:flutter/material.dart';
    import 'package:vcare/Screens/tetxing1.dart';
    
    
    class TaskApp extends StatefulWidget {
        final ListTask  listTask;
      const TaskApp({Key? key,required this.listTask}) : super(key: key);
    
      @override
      State<TaskApp> createState() => _TaskAppState();
    }
    
    class _TaskAppState extends State<TaskApp> {
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
    
          body: Padding(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 10),
               // Logo(),
                SizedBox(height: 0),
                //SearchBar(),
                SizedBox(height: 15),
                Column(
                  children: [
                    Text(
                      'All tasks',
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0),
                    )
                  ],
                ),
                SizedBox(height: 15),
                ListTask(),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton.extended(
            onPressed: () {
            ListTask().method1(context);
    
            },
            label: const Text('Add Task'),
            icon: const Icon(Icons.add),
            backgroundColor: Colors.blue[900],
          ),
        );
      }
    }
    

    ListTask.dart

    import 'package:flutter/material.dart';
    
    class ListTask extends StatefulWidget {
    
     method1(context) => createState().displayTextInputDialog(context);
      @override
      _ListTaskState createState() => _ListTaskState();
    }
    
    class _ListTaskState extends State<ListTask> {
    
      final List<String> tasks = ['masu', 'adasf', 'wfqf', 'santha'];
    
      final TextEditingController _textFieldController = TextEditingController();
    
      void addItemToList() {
        setState(() {
          tasks.insert(0, _textFieldController.text);
        });
      }
     
    
      @override
      Widget build(BuildContext context) {
        return Container(
          height: 320,
          width: double.maxFinite,
          child: ListView.builder(
            padding: EdgeInsets.only(bottom: 10),
            itemCount: tasks.length,
            itemBuilder: (context, index) {
              return Card(
                elevation: 1,
                color: Colors.grey[200],
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ExpansionTile(title: Text(tasks[index]), children: <Widget>[
                      ListTile(
                        title: Text(tasks[index]),
                      )
                    ]),
                  ],
                ),
              );
            },
          ),
        );
      }
    
        Future<void> displayTextInputDialog(BuildContext context) async {
        return showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text('TextField in Dialog'),
                content: TextField(
                  onChanged: (value) {
                    setState(() {
                      // valueText = value;
                    });
                  },
                  controller: _textFieldController,
                  decoration: InputDecoration(hintText: "Text Field in Dialog"),
                ),
                actions: <Widget>[
                  FlatButton(
                    color: Colors.red,
                    textColor: Colors.white,
                    child: Text('CANCEL'),
                    onPressed: () {
                      setState(() {
                        Navigator.pop(context);
                      });
                    },
                  ),
                  FlatButton(
                    color: Colors.green,
                    textColor: Colors.white,
                    child: Text('OK'),
                    onPressed: () {
                      setState(() {
                        addItemToList();
                        Navigator.pop(context);
                      });
                    },
                  ),
                ],
              );
            });
      }
    }
    

    if you find this solution helpful please mark as accepted answer