【问题标题】:Dropdown resets all fields in FlutterDropdown 重置 Flutter 中的所有字段
【发布时间】:2021-10-29 13:05:09
【问题描述】:

我目前正在开发一个任务应用程序。每当我从下拉列表中选择优先级或日期时,上面文本字段中的值都会重置为 null,并且所选日期和优先级也会设置回默认值。

真的很想得到一些帮助。 代码 sn-p 如下 -

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:ssms_new/Models/ToDoModel.dart';
import 'package:http/http.dart' as http;
import 'package:date_time_picker/date_time_picker.dart';
import 'package:ssms_new/Tasks/AllTasksTabsView.dart';

import '../Configurations/configurations.dart';

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

  @override
  _AddTaskModalSheetState createState() => _AddTaskModalSheetState();
}

class _AddTaskModalSheetState extends State<AddTaskModalSheet> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    var screenHeight = MediaQuery.of(context).size.height;
    var screenWidth = MediaQuery.of(context).size.width;
    final TextEditingController taskTitle = TextEditingController();
    final TextEditingController taskNotes = TextEditingController();

    String selectedPriority = "Normal";
    String _dueDate = "${DateTime.now().toString()}";

    Future<ToDoModel?> postNewTask() async {
      var response;
      String encodedPath = "task/new/$savedUserID";
      if (devMode == "development") {
        response = await http.post(Uri.parse('$devUrl$encodedPath'), body: {
          "name": taskTitle.text,
          "note": taskNotes.text,
          "title": taskTitle.text,
          "done": "0",
          "priority": "$selectedPriority",
          "due_date": "$_dueDate",
          "TaskOwner": "$savedUserID",
          "img": "NA",
          "studentId": "$savedUserID",
          "assignerId": "0",
          "closeTaskNotes": "NA",
        });
      } else {
        print(selectedPriority);
        response = await http.post(Uri.parse('$prodUrl$encodedPath'), body: {
          "name": taskTitle.text,
          "note": taskNotes.text,
          "title": taskTitle.text,
          "done": "0",
          "priority": "$selectedPriority",
          "due_date": "$_dueDate",
          "TaskOwner": "$savedUserID",
          "img": "NA",
          "studentId": "$savedUserID",
          "assignerId": "0",
          "closeTaskNotes": "NA",
        });
      }

      print(response.statusCode);
      String responseString = response.body;
      toDoFromJson(responseString);

      print(response.body);
      return null;
    }

    

    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom),
              color: Color(0xff737373),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                ),
                child: Column(children: [
                  SizedBox(height: 20),
                  Text(
                    "Add New Task",
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 20),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        TextField(
                          controller: taskTitle,
                          decoration: InputDecoration(
                            labelText: "Task Title",
                            border: OutlineInputBorder(),
                          ),
                        ),
                        SizedBox(height: 10),
                        TextField(
                          controller: taskNotes,
                          maxLines: 3,
                          decoration: InputDecoration(
                            labelText: "Task Notes",
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 2),
                  Container(
                    padding: EdgeInsets.only(left: 4, right: 3),
                    width: screenWidth / 1.05,
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 2),
                        borderRadius: BorderRadius.circular(5)),
                    child: DropdownButtonFormField(
                      items: priorityList.map((String category) {
                        return DropdownMenuItem(
                            value: category,
                            child: Row(
                              children: <Widget>[
                                Text(category),
                              ],
                            ));
                      }).toList(),
                      onTap: () =>
                          FocusManager.instance.primaryFocus!.unfocus(),
                      onChanged: (newValue) {
                        // do other stuff with _category
                        selectedPriority = newValue.toString();
                      },
                      value: selectedPriority,
                    ),
                  ),
                  DateTimePicker(
                    type: DateTimePickerType.date,
                    dateMask: 'd MMM, yyyy',
                    initialValue: DateTime.now().toString(),
                    firstDate: DateTime.now(),
                    lastDate: DateTime(2100),
                    icon: Icon(Icons.event),
                    dateLabelText: 'Date',
                    onChanged: (val) {
                      _dueDate = val;
                    },
                    onSaved: (val) {
                      _dueDate = val!;
                    },
                  ), //Select Work Date
                  SizedBox(height: 10),
                  ElevatedButton(
                      style:
                          ElevatedButton.styleFrom(primary: Color(0xffe9c46a)),
                      onPressed: () {
                        postNewTask();
                        Navigator.pushAndRemoveUntil(context,
                            MaterialPageRoute(builder: (context) {
                          return AllTasksTabView(id: savedUserID);
                        }), (route) => true);
                      }, //TODO: add task here
                      child: Text("Add Task",
                          style: TextStyle(color: Colors.black))),
                  SizedBox(height: 30),
                ]),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 请包含完整的小部件代码。
  • 已更新完整代码。

标签: flutter dart flutter-layout flutter-dependencies flutter-test


【解决方案1】:

您将所有状态存储在 build 方法中,因此无论何时重建小部件,所有状态都会被覆盖。

请看this tutorial以了解StatefulWidgetStatelessWidget之间的区别以及如何添加交互性/

【讨论】:

  • 我想我做错了什么,我又试了一次,效果很好,谢谢伙计!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
相关资源
最近更新 更多