Flutter Save multiple forms Data, from a another widget

二次信任 提交于 2021-02-11 12:32:30

问题


I am trying to display a list of flutter forms with a list view builder. UI for which I have already done.

I want to access the data now for each form and validate, can someone guide me?

i tried different approaches and checking similar posts on StackOverflow, but was not able to find any solution for the same.

entries_widget.dart - where the form is created

class EntriesWidget extends StatefulWidget {
  EntriesWidget({Key key}) : super(key: key);

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

class EntriesWidgetState extends State<EntriesWidget> {
  List<EntryCard> entryCardList = [];
  int count = 0;

  void removeEntryCard(index) {
    print("inside remove function ${index}");
    setState(() {
      entryCardList.remove(index);
      // index++;
    });
  }

  void addEntryCard() {
    setState(() {
      entryCardList.add(
        EntryCard(removeEntryCard, index: entryCardList.length),
      );
    });
  }

  @override
  void initState() {
    // addEntryCard(); //Initialize with 1 item
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('1. HRD Timesheet (Systems)', style: kDefaultTitleStyle),
              GestureDetector(
                onTap: addEntryCard,
                child: Chip(
                  label: Text('+ Add Task'),
                  backgroundColor: Colors.grey,
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                ),
              ),
            ],
          ),
          SizedBox(height: 10.0),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: kPrimaryAppColor),
            ),
            child: Padding(
              padding: const EdgeInsets.all(6.0),
              child: Column(
                children: [
                  ListView(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    children: [
                      ...entryCardList,
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void saveForm2() {
    print("inside save form");
    // if (formKey.currentState.validate()) {
    //   formKey.currentState.save();
    //   print(widget.taskEntry.taskName);
    //   print(widget.taskEntry.taskHours);
    // }
  }
}

class EntryCard extends StatefulWidget {
  final TaskEntry taskEntry;
  final int index;
  final Function(EntryCard) removeEntryCard;
  // final TextEditingController hours;
  // final TextEditingController task;

  const EntryCard(this.removeEntryCard,
      {Key key, @required this.index, this.taskEntry})
      : super(key: key);

  void remove() {
    print("Called remove on " + this.hashCode.toString());

    removeEntryCard(this);
  }

  @override
  EntryCardState createState() {
    return EntryCardState(index, remove);
  }
}

class EntryCardState extends State<EntryCard> {
  final int entryIndex;
  final Function() remove;
  final formKey = GlobalKey<FormState>();

  EntryCardState(this.entryIndex, this.remove);
  @override
  Widget build(BuildContext context) {
    return Form(
      key: formKey,
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: TextFormField(
                  //  initialValue: widget.user.fullName,
                  onSaved: (val) => widget.taskEntry.taskHours = val,
                  validator: (val) => val.length > 1 ? null : 'Invalid Field',
                  // controller: widget.hours,
                  decoration: InputDecoration(
                    hintText: "Hours ${widget.index}",
                    isDense: true,
                    // border: OutlineInputBorder(),
                  ),
                ),
              ),
              SizedBox(width: 5.0),
              Expanded(
                child: TextFormField(
                  onSaved: (val) => widget.taskEntry.taskName = val,
                  validator: (val) => val.length > 1 ? null : 'Invalid Field',
                  // controller: widget.task,
                  decoration: InputDecoration(
                    hintText: "Task Name ${widget.index}",
                    // border: OutlineInputBorder(),
                    isDense: true,
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.remove),
                color: kPrimaryAppColor,
                onPressed: () {
                  widget.remove();
                },
              )
            ],
          ),
          SizedBox(height: 5.0),
          // TextFormField(
          //   decoration: InputDecoration(
          //     hintText: "This is Remarks ${index}",
          //     border: O`utlineInputBorder(),
          //   ),
          // ),
          // SizedBox(height: 10.0),
        ],
      ),
    );
  }

  void saveForm() {
    print("inside save form");
    if (formKey.currentState.validate()) {
      formKey.currentState.save();
      print(widget.taskEntry.taskName);
      print(widget.taskEntry.taskHours);
    }
  }
}

add_timesheet_page.dart

final key = new GlobalKey<EntriesWidgetState>();
final keyForm = GlobalKey<EntryCardState>();

class AddTimesheet extends StatefulWidget {
  @override
  _AddTimesheetState createState() => _AddTimesheetState();
}

class _AddTimesheetState extends State<AddTimesheet> {
  String dropdownValue = 'Week 1';
  // List<TaskEntry> taskEntries = [];
  List<EntriesWidget> entriesWidgets = [];
  // var cards = <Card>[];

  submitData() {
    print("inside submit");
    keyForm.currentState.saveForm();
    key.currentState.saveForm2();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        context,
        titleText: "Add Log",
        isChipLayout: false,
      ),
      body: SingleChildScrollView(
        physics: ScrollPhysics(),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Text(
                  'Naman Ambavi - 1405',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 20.0,
                    color: kPrimaryAppColor,
                  ),
                ),
              ),
              SizedBox(height: 15.0),
              Text('Week', style: kDefaultTitleStyle),
              Container(
                width: 300,
                child: DropdownButton(
                  isExpanded: true,
                  value: dropdownValue,
                  icon: Icon(Icons.arrow_downward),
                  iconSize: 24,
                  elevation: 16,
                  style: TextStyle(color: kPrimaryAppColor),
                  underline: Container(
                    height: 2,
                    color: kPrimaryAppColor,
                  ),
                  onChanged: (String newValue) {
                    setState(() {
                      dropdownValue = newValue;
                    });
                  },
                  items: <String>[
                    'Week 1',
                    'Week 2 (1st Oct - 10th Oct)',
                    'Week 3'
                  ].map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),
              ),
              SizedBox(
                height: 18.0,
              ),
              const Divider(
                color: kPrimaryAppColor,
                thickness: 0.5,
              ),
              Text('Select Department', style: kDefaultTitleStyle),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "IT",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "PMT",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "AV",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 15.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'IT Hours for week: 35/40 hours',
                    style: kDefaultParagraphStyle,
                  ),
                  Chip(
                    label: Text('View Log'),
                    backgroundColor: Colors.grey,
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                ],
              ),
              SizedBox(height: 20.0),
              // Expanded(
              //   child: ListView.builder(
              //     itemCount: cards.length,
              //     itemBuilder: (BuildContext context, int index) {
              //       return cards[index];
              //     },
              //   ),
              // ),
              SizedBox(height: 20.0),
              // EntriesWidget(),
              Flexible(
                child: ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: 2,
                  itemBuilder: (context, index) {
                    return EntriesWidget(key: keyForm);
                  },
                ),
              ),
              SizedBox(height: 20.0),
              Center(
                child: FlatButton(
                  color: kPrimaryAppColor,
                  textColor: Colors.white,
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.black,
                  padding: EdgeInsets.all(8.0),
                  splashColor: kPrimaryAppColor,
                  onPressed: submitData,
                  child: Text(
                    "Add Log",
                    style: TextStyle(fontSize: 20.0),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void onSave() {
    // entries.forEach((form) => allValid = allValid && form.isValid());
    // var data = taskEntries.map((it) => it.taskEntries).toList();
  }
}

task_entry_model.dart

class TaskEntry {
  String taskName;
  String taskHours;

  TaskEntry({this.taskName = '', this.taskHours = ''});
  String toString() {
    return 'Student: {TaskName: $taskName, TaskHours: $taskHours}';
  }
}


    

回答1:


You can copy paste run full code below
It's too long to describe all the detail, you directly reference full code and working demo below
Step 1: You need List<GlobalKey<EntriesWidgetState>> for EntriesWidget(key: key[index]);

List<GlobalKey<EntriesWidgetState>> key = [
  GlobalKey<EntriesWidgetState>(),
  GlobalKey<EntriesWidgetState>()
];
... 
Flexible(
        child: ListView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemCount: 2,
          itemBuilder: (context, index) {
            return EntriesWidget(key: key[index]);
          },
        ),
      ),

Step 2: put List<GlobalKey<EntryCardState>> keyForm in EntriesWidgetState and use removeAt

class EntriesWidgetState extends State { List entryCardList = []; int count = 0; List<GlobalKey> keyForm = []; int keyFormIndex = -1;

  void removeEntryCard(index, EntryCard) {
    print("inside remove function ${index}");
    keyFormIndex = keyFormIndex - 1;

    var pos = entryCardList.indexOf(EntryCard);
    print("pos $pos");
    setState(() {
      entryCardList.removeAt(pos);
      keyForm.removeAt(pos);
      // index++;
    });
  }

  void addEntryCard() {
    setState(() {
      keyForm.add(GlobalKey<EntryCardState>());
      keyFormIndex = keyFormIndex + 1;

      entryCardList.add(
        EntryCard(
          removeEntryCard,
          key: keyForm[keyFormIndex],
          index: entryCardList.length,
          taskEntry: TaskEntry(),
        ),
      );
    });
  }

Step 3: For Loop each key and call saveForm

submitData() {
    print("inside submit");

    key.forEach((element) {
      element.currentState.saveForm2();
    });
  } 
...  
void saveForm2() {
    keyForm.forEach((element) {
      element.currentState.saveForm();
    });
    

working demo

full code

import 'package:flutter/material.dart';

const Color kPrimaryAppColor = Colors.blue;
TextStyle kDefaultTitleStyle = TextStyle(color: Colors.black);
TextStyle kDefaultParagraphStyle = TextStyle(color: Colors.black);

class TaskEntry {
  String taskName;
  String taskHours;

  TaskEntry({this.taskName = '', this.taskHours = ''});
  String toString() {
    return 'Student: {TaskName: $taskName, TaskHours: $taskHours}';
  }
}

List<GlobalKey<EntriesWidgetState>> key = [
  GlobalKey<EntriesWidgetState>(),
  GlobalKey<EntriesWidgetState>()
];
//final keyForm = GlobalKey<EntryCardState>();

class AddTimesheet extends StatefulWidget {
  @override
  _AddTimesheetState createState() => _AddTimesheetState();
}

class _AddTimesheetState extends State<AddTimesheet> {
  String dropdownValue = 'Week 1';
  // List<TaskEntry> taskEntries = [];
  List<EntriesWidget> entriesWidgets = [];
  // var cards = <Card>[];

  submitData() {
    print("inside submit");

    key.forEach((element) {
      element.currentState.saveForm2();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        physics: ScrollPhysics(),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Text(
                  'Naman Ambavi - 1405',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 20.0,
                    color: kPrimaryAppColor,
                  ),
                ),
              ),
              SizedBox(height: 15.0),
              Text('Week', style: kDefaultTitleStyle),
              Container(
                width: 300,
                child: DropdownButton(
                  isExpanded: true,
                  value: dropdownValue,
                  icon: Icon(Icons.arrow_downward),
                  iconSize: 24,
                  elevation: 16,
                  style: TextStyle(color: kPrimaryAppColor),
                  underline: Container(
                    height: 2,
                    color: kPrimaryAppColor,
                  ),
                  onChanged: (String newValue) {
                    setState(() {
                      dropdownValue = newValue;
                    });
                  },
                  items: <String>[
                    'Week 1',
                    'Week 2 (1st Oct - 10th Oct)',
                    'Week 3'
                  ].map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),
              ),
              SizedBox(
                height: 18.0,
              ),
              const Divider(
                color: kPrimaryAppColor,
                thickness: 0.5,
              ),
              Text('Select Department', style: kDefaultTitleStyle),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "IT",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "PMT",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                  FlatButton(
                    color: kPrimaryAppColor,
                    textColor: Colors.white,
                    disabledColor: Colors.grey,
                    disabledTextColor: Colors.black,
                    padding: EdgeInsets.all(8.0),
                    splashColor: kPrimaryAppColor,
                    onPressed: () {
                      /*...*/
                    },
                    child: Text(
                      "AV",
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 15.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'IT Hours for week: 35/40 hours',
                    style: kDefaultParagraphStyle,
                  ),
                  Chip(
                    label: Text('View Log'),
                    backgroundColor: Colors.grey,
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                ],
              ),
              SizedBox(height: 20.0),
              // Expanded(
              //   child: ListView.builder(
              //     itemCount: cards.length,
              //     itemBuilder: (BuildContext context, int index) {
              //       return cards[index];
              //     },
              //   ),
              // ),
              SizedBox(height: 20.0),
              // EntriesWidget(),
              Flexible(
                child: ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: 2,
                  itemBuilder: (context, index) {
                    return EntriesWidget(key: key[index]);
                  },
                ),
              ),
              SizedBox(height: 20.0),
              Center(
                child: FlatButton(
                  color: kPrimaryAppColor,
                  textColor: Colors.white,
                  disabledColor: Colors.grey,
                  disabledTextColor: Colors.black,
                  padding: EdgeInsets.all(8.0),
                  splashColor: kPrimaryAppColor,
                  onPressed: submitData,
                  child: Text(
                    "Add Log",
                    style: TextStyle(fontSize: 20.0),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void onSave() {
    // entries.forEach((form) => allValid = allValid && form.isValid());
    // var data = taskEntries.map((it) => it.taskEntries).toList();
  }
}

class EntriesWidget extends StatefulWidget {
  EntriesWidget({Key key}) : super(key: key);

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

class EntriesWidgetState extends State<EntriesWidget> {
  List<EntryCard> entryCardList = [];
  int count = 0;
  List<GlobalKey<EntryCardState>> keyForm = [];
  int keyFormIndex = -1;

  void removeEntryCard(index, EntryCard) {
    print("inside remove function ${index}");
    keyFormIndex = keyFormIndex - 1;

    var pos = entryCardList.indexOf(EntryCard);
    print("pos $pos");
    setState(() {
      entryCardList.removeAt(pos);
      keyForm.removeAt(pos);
      // index++;
    });
  }

  void addEntryCard() {
    setState(() {
      keyForm.add(GlobalKey<EntryCardState>());
      keyFormIndex = keyFormIndex + 1;

      entryCardList.add(
        EntryCard(
          removeEntryCard,
          key: keyForm[keyFormIndex],
          index: entryCardList.length,
          taskEntry: TaskEntry(),
        ),
      );
    });
  }

  @override
  void initState() {
    // addEntryCard(); //Initialize with 1 item
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('1. HRD Timesheet (Systems)', style: kDefaultTitleStyle),
              GestureDetector(
                onTap: addEntryCard,
                child: Chip(
                  label: Text('+ Add Task'),
                  backgroundColor: Colors.grey,
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                ),
              ),
            ],
          ),
          SizedBox(height: 10.0),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: kPrimaryAppColor),
            ),
            child: Padding(
              padding: const EdgeInsets.all(6.0),
              child: Column(
                children: [
                  ListView(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    children: [
                      ...entryCardList,
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void saveForm2() {
    keyForm.forEach((element) {
      element.currentState.saveForm();
    });
    print("inside save form");
    // if (formKey.currentState.validate()) {
    //   formKey.currentState.save();
    //   print(widget.taskEntry.taskName);
    //   print(widget.taskEntry.taskHours);
    // }
  }
}

class EntryCard extends StatefulWidget {
  final TaskEntry taskEntry;
  final int index;
  final Function(int, EntryCard) removeEntryCard;
  // final TextEditingController hours;
  // final TextEditingController task;

  const EntryCard(this.removeEntryCard,
      {Key key, @required this.index, this.taskEntry})
      : super(key: key);

  void remove(int entryIndex) {
    print("Called remove on $entryIndex" + this.hashCode.toString());

    removeEntryCard(entryIndex, this);
  }

  @override
  EntryCardState createState() {
    return EntryCardState(index, remove);
  }
}

class EntryCardState extends State<EntryCard> {
  final int entryIndex;
  final Function remove;
  final formKey = GlobalKey<FormState>();

  EntryCardState(this.entryIndex, this.remove);
  @override
  Widget build(BuildContext context) {
    return Form(
      key: formKey,
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: TextFormField(
                  //  initialValue: widget.user.fullName,
                  onSaved: (val) => widget.taskEntry.taskHours = val,
                  validator: (val) => val.length > 1 ? null : 'Invalid Field',
                  // controller: widget.hours,
                  decoration: InputDecoration(
                    hintText: "Hours ${widget.index}",
                    isDense: true,
                    // border: OutlineInputBorder(),
                  ),
                ),
              ),
              SizedBox(width: 5.0),
              Expanded(
                child: TextFormField(
                  onSaved: (val) => widget.taskEntry.taskName = val,
                  validator: (val) => val.length > 1 ? null : 'Invalid Field',
                  // controller: widget.task,
                  decoration: InputDecoration(
                    hintText: "Task Name ${widget.index}",
                    // border: OutlineInputBorder(),
                    isDense: true,
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.remove),
                color: kPrimaryAppColor,
                onPressed: () {
                  widget.remove(entryIndex);
                },
              )
            ],
          ),
          SizedBox(height: 5.0),
          // TextFormField(
          //   decoration: InputDecoration(
          //     hintText: "This is Remarks ${index}",
          //     border: O`utlineInputBorder(),
          //   ),
          // ),
          // SizedBox(height: 10.0),
        ],
      ),
    );
  }

  void saveForm() {
    print("inside save form");
    if (formKey.currentState.validate()) {
      formKey.currentState.save();
      print(widget.taskEntry.taskName);
      print(widget.taskEntry.taskHours);
    }
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AddTimesheet(),
    );
  }
}


来源:https://stackoverflow.com/questions/65856420/flutter-save-multiple-forms-data-from-a-another-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!