在Flutter中使用警报对话框文本字段向ListView添加项目

vpfxa7rd  于 2023-01-02  发布在  Flutter
关注(0)|答案(2)|浏览(108)

因此,我试图有一个页面,你点击浮动操作按钮,弹出对话框/警报对话框出现一个文本字段,你输入名称,它在列表视图中创建一个项目,我也希望该项目是可点击的,并前往另一个页面,该名称作为新的应用程序栏名称。
这是我的代码,但它没有创建任何东西:

import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

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

  @override
  State<lists> createState() => _listsState();
}

class _listsState extends State<lists> {
  @override
  Widget build(BuildContext context) {
    String _newItemName = '';
    final List<String> _items = [];
    final textController = TextEditingController();
    int _currentIndex = 0;

    return Scaffold(
      body: _items.length > 0
          ? ListView.builder(
              itemCount: _items.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text('${_items[index]}'),
                );
              },
            )
          : const Center(
              child: Text("You currently have no classes. Add from below."),
            ),
      floatingActionButton: SpeedDial(
        animatedIcon: AnimatedIcons.menu_arrow,
        spacing: 6,
        spaceBetweenChildren: 6,
        backgroundColor: const Color.fromARGB(255, 22, 37, 50),
        foregroundColor: const Color.fromARGB(255, 255, 255, 255),
        children: [
          SpeedDialChild(
              child: const Icon(Icons.group_add), label: "add student"),
          SpeedDialChild(
            child: const Icon(Icons.school),
            label: "add class",
            onTap: () {
              showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: const Text('Add a new class'),
                    content: TextField(
                      controller: textController,
                      autofocus: true,
                      decoration: const InputDecoration(
                          hintText: "Enter the name of the class."),
                    ),
                    actions: [
                      TextButton(
                        child: Text('Cancel'),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      TextButton(
                        child: Text('Add'),
                        onPressed: () {
                          Navigator.pop(context, textController.text);
                        },
                      ),
                    ],
                  );
                },
              );
            },
          )
        ],
      ),
    );
  }
}
cmssoen2

cmssoen21#

Add操作中,使用setState更新_list的值以包含该项

return AlertDialog(
         title: const Text('Add a new class'),
         content: TextField(
                    controller: textController,
                    autofocus: true,
                    decoration: const InputDecoration(
                          hintText: "Enter the name of the class."),
                    ),
                    actions: [
                      TextButton(
                        child: Text('Cancel'),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      TextButton(
                        child: Text('Add'),
                        onPressed: () {
                          setState((){
                             _items.add(textController.text)  // 👈 add list item to the list
                           });
                          Navigator.pop(context, textController.text);
                        },
                      ),
                    ],
                  );
flvlnr44

flvlnr442#

  • 如果您想等待showDialog返回结果,则需要使用async await。
  • _items变量不能是final,因为final不可变。
  • 如果要使用setState,必须在build方法外定义变量,build方法内的_items并初始化为空So _items将在重绘UI时重新初始化。
  • textEditController不应在build方法内部定义,其生命周期应进行管理。
import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

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

  @override
  State<lists> createState() => _listsState();
}

class _listsState extends State<lists> {
  List<String> _items = [];
  late TextEditingController _textController;
  int _currentIndex = 0;
  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _items.length > 0
          ? ListView.builder(
              itemCount: _items.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text('${_items[index]}'),
                );
              },
            )
          : const Center(
              child: Text("You currently have no classes. Add from below."),
            ),
      floatingActionButton: SpeedDial(
        animatedIcon: AnimatedIcons.menu_arrow,
        spacing: 6,
        spaceBetweenChildren: 6,
        backgroundColor: const Color.fromARGB(255, 22, 37, 50),
        foregroundColor: const Color.fromARGB(255, 255, 255, 255),
        children: [
          SpeedDialChild(
              child: const Icon(Icons.group_add), label: "add student"),
          SpeedDialChild(
            child: const Icon(Icons.school),
            label: "add class",
            onTap: () async {
              final result = await showDialog(
                context: context,
                builder: (context) {
                  return AlertDialog(
                    title: const Text('Add a new class'),
                    content: TextField(
                      controller: _textController,
                      autofocus: true,
                      decoration: const InputDecoration(
                          hintText: "Enter the name of the class."),
                    ),
                    actions: [
                      TextButton(
                        child: Text('Cancel'),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      TextButton(
                        child: Text('Add'),
                        onPressed: () {
                          Navigator.pop(context, _textController.text);
                        },
                      ),
                    ],
                  );
                },
              );
              if (result != null) {
                result as String;
                setState(() {
                  _items.add(result);
                });
              }
            },
          )
        ],
      ),
    );
  }
}

相关问题