0

每当我通过在这些表单字段中填写数据进行提交时,数据都保存得很好,但是添加新字段并提交后,数据没有正确保存。

在第一次点击得到这个:

flutter: Total = 2 flutter: Friends = (Jarry, James) flutter: RollNo. = (1244, 1245)

添加新字段后得到这个:

flutter: Total = 3 flutter: Friends = (, Jarry, Oliver) flutter: RollNo. = (, 1244, 1246)

这是我的代码。

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  static List<TestModel> friendsList = [];

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Dynamic TextFormFields'),
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // name textfield
                Padding(
                  padding: const EdgeInsets.only(right: 32.0),
                  child: TextFormField(
                    controller: _nameController,
                    decoration: InputDecoration(hintText: 'Enter your name'),
                    validator: (v) {
                      if (v!.trim().isEmpty) return 'Please enter something';
                      return null;
                    },
                  ),
                ),
                SizedBox(
                  height: 20,
                ),

                ..._getFriends(),

                SizedBox(
                  height: 40,
                ),
                MaterialButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();
                      print('Total = ${_MyFormState.friendsList.length}');
                      print('Friends = ${_MyFormState.friendsList.map((e) => e.friend)}');
                      print('RollNo. = ${_MyFormState.friendsList.map((e) => e.rollNo)}');
                    }
                  },
                  child: Text('Submit'),
                  color: Colors.green,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// get firends text-fields
  List<Widget> _getFriends() {
    List<Widget> friendsTextFields = [];
    for (int i = 0; i <= friendsList.length; i++) {
      friendsTextFields.add(
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          child: Row(
            children: [
              Expanded(child: FriendTextFields(i)),
              SizedBox(
                width: 16,
              ),
              // we need add button at last friends row
              _addRemoveButton(i == friendsList.length, i),
            ],
          ),
        ),
      );
    }
    return friendsTextFields;
  }

  /// add / remove button
  Widget _addRemoveButton(bool add, int index) {
    return InkWell(
      onTap: () {
        if (add) {
          print('add');
          friendsList.insert(0, TestModel());
        } else
          friendsList.removeAt(index);
        print('remove');
        setState(() {});
      },
      child: Container(
        width: 30,
        height: 30,
        decoration: BoxDecoration(
          color: (add) ? Colors.green : Colors.red,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Icon(
          (add) ? Icons.add : Icons.remove,
          color: Colors.white,
        ),
      ),
    );
  }
}

class FriendTextFields extends StatefulWidget {
  final int index;
  FriendTextFields(this.index);
  @override
  _FriendTextFieldsState createState() => _FriendTextFieldsState();
}

class _FriendTextFieldsState extends State<FriendTextFields> {
  late TestModel testModel;

  @override
  void initState() {
    super.initState();
    testModel = TestModel();
  }

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      testModel = _MyFormState.friendsList[widget.index];
    });

    return Column(
      children: [
        TextFormField(
          onChanged: (v) =>
              _MyFormState.friendsList[widget.index].friend = v,
          decoration: InputDecoration(hintText: 'Enter your friend\'s name'),
          validator: (v) {
            if (v!.trim().isEmpty) return 'Please enter something';
            return null;
          },
        ),
        TextFormField(
          onChanged: (v) => _MyFormState.friendsList[widget.index].rollNo = v,
          decoration: InputDecoration(hintText: 'Enter your collage name'),
          validator: (v) {
            if (v!.trim().isEmpty) return 'Please enter something';
            return null;
          },
        ),
      ],
    );
  }
}

class TestModel {
  TestModel({
    this.friend: '',
    this.rollNo: '',
  });
  String friend;
  String rollNo;
}

界面截图 在此处输入图像描述

4

0 回答 0