如何在flutter中将方法传递到另一个类中

发布于 2025-01-14 23:45:26 字数 4369 浏览 1 评论 0原文

我尝试使用 flutter 创建一个任务应用程序,所以我在 DialogBox 中创建了一个文本字段,我的目标是当我在文本字段中添加一些文本时,当我单击“确定”按钮时,我需要在列表中显示该文本。但我不知道如何调用另一个类中的方法,我添加了两个类。

ListTask 类

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 类

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],
      ),
    );
  }
}

TaskApp 类中该方法的调用点:

Calling TaskApp 类中该方法的点

方法:

Method

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不喜欢何必死缠烂打 2025-01-21 23:45:26

你可以尝试一下,它会从 TaskApp(StatefulWidget) 小部件调用 ListTask(StatefulWidget) 中定义的方法。

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);
                  });
                },
              ),
            ],
          );
        });
  }
}

如果您发现此解决方案有帮助,请标记为已接受的答案

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文