2

вот как он работает: gif

ошибка в том, что когда начинаю удалять форму с середины или сначала, как я понял, не удаляется именно та форма которая была нажата первой, что мне надо написать правильно?

вот мой код:

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

class FormData extends StatefulWidget {
  @override
  _FormDataState createState() => _FormDataState();
}

class _FormDataState extends State<FormData> {
  List<Data> _data = [];
  List<Widget> _children = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AddPage'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.save),
            onPressed: () {},
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: <Widget>[
              Container(
                child: _children.length <= 0
                    ? Text(
                        'tap [+] button for add',
                        style: TextStyle(color: Colors.yellow, fontSize: 18.0),
                      )
                    : Column(
                        children: _children,
                      ),
              ),
              Container(
                child: RaisedButton(
                  child: Icon(Icons.add),
                  onPressed: () => onAddForm(_data.length),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
    void onAddForm(int keyValue) {
    setState(() {
      _data.add(Data());
    });
    _children = List.from(_children)
      ..add(Card(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              flex: 85,
              child: Column(
                children: <Widget>[
                  TextField(
                    style: TextStyle(color: Colors.lime[600]),
                    onChanged: (val) {
                      onChangedName(keyValue, val);
                    },
                    decoration: InputDecoration(
                        hintText: 'name',
                        hintStyle: TextStyle(color: Colors.lime[900])),
                  ),
                  TextField(
                    keyboardType: TextInputType.number,
                    onChanged: (val) {
                      onChangedNumber(keyValue, val);
                    },
                    decoration: InputDecoration(
                      hintText: 'phoneNumber',
                      hintStyle: TextStyle(color: Colors.grey)
                      ),
                  )
                ],
              ),
            ),
            Expanded(
              flex: 15,
              child: FlatButton(
                child: Stack(
                  children: <Widget>[
                    Icon(Icons.delete, size: 28,),
                    Positioned(
                      top: -20,
                      right: -15,
                      child: CircleAvatar(
                        radius: 12,
                        backgroundColor: Colors.red,
                        child: Text(
                          '$keyValue',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    )
                  ],
                  overflow: Overflow.visible,
                ),
                onPressed: ()=>onDelete(keyValue),
              ),
            )
          ],
        ),
      ));
  }

  void onDelete(int index) {
    setState(() {
      _data.removeAt(index);
      _children.removeAt(index);
    });
    print(_data);
  }

  onChangedName(int index, String record) {
    setState(() {
      _data[index].phoneNumber = record;
    });
  }

  onChangedNumber(int index, String record) {
    setState(() {
      _data[index].phoneNumber = record;
    });
  }
}
1
  • вот ошибка с консоли: RangeError (index): Invalid value: Only valid value is 0: 2 тоесть цифра 2 в ошибке – индекс которая была нажата первой 28 ноя 2019 в 9:35

1 ответ 1

1

Проблема в методе onAddForm(int keyValue), вы передаете keyValue и фиксируете его в _children (Что и приводит к неправильному удалению если идти не по порядку). Когда вы вызываете метод onDelete(int index) вы передаете keyValue из _children, а должны передавать текший индекс _data. Более подробно можно посмотреть при дебаге.

Решение: передавать не индекс, а модель:

void onDelete(Data data) {
  setState(() {
    _data.remove(data);
    _children.remove(data);
  });
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.