从数组中删除特定项目会删除 UI 中的错误项目

Gab*_*iel 2 dart flutter

我为此苦苦挣扎了几天,但无法弄清楚。我有一个简单的小部件,我想在其中动态添加和删除输入(对于组/代表)。问题是,如果我删除第一个项目,那么最后一个项目就会从 UI 中删除。

我为应用程序创建了一个 dartpad:dartpad

我的 main.dart:

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SetBuilderWidget();
  }
}

class TempSet {
  int weight;
  int rep;
  int order;

  TempSet(this.order, this.weight, this.rep);
}

class SetBuilderWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SetBuilderWidgetState();
}

class _SetBuilderWidgetState extends State<SetBuilderWidget> {
  final sets = [];
  final List<TempSet> tempSet = [];

  Widget _row(int index) {
    return Row(
      children: <Widget>[
        Text("Set $index"),
        Flexible(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 40),
            child: TextField(
              decoration: InputDecoration(
                labelText: "Rep count",
              ),
            ),
          ),
        ),
        IconButton(
          icon: Icon(Icons.delete),
          onPressed: () => _removeSet(index),
        ),
      ],
    );
  }

  List<Widget> _rows() {
    return tempSet.map((s) => _row(s.order)).toList();
  }

  void _addSet() {
    if (tempSet.length == 0) {
      tempSet.add(TempSet(0, null, null));
    } else {
      final lastSet = tempSet.last;
      tempSet.add(TempSet(tempSet.indexOf(lastSet) + 1, null, null));
    }
  }

  void _removeSet(int index) {
    setState(() {
      tempSet.removeAt(index);
      _updateIndexes();
    });
  }

  void _updateIndexes() {
    tempSet.asMap().forEach((index, s) {
      s.order = index;
    });
  }

  @override
  void initState() {
    _addSet();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ..._rows(),
        RaisedButton(
          onPressed: () {
            setState(() {
              _addSet();
            });
          },
          child: Text("Add set"),
        )
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

问题:

在此输入图像描述

eas*_*ccy 5

您应该将这些文本字段的状态保存在地图中。

解决方案

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SetBuilderWidget();
  }
}

class TempSet {
  int weight;
  int rep;
  int order;

  TempSet(this.order, this.weight, this.rep);
}

class SetBuilderWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SetBuilderWidgetState();
}

class _SetBuilderWidgetState extends State<SetBuilderWidget> {
  final sets = [];
  final List<TempSet> tempSet = [];

  Widget _row(int index, int rep) {
    TextEditingController _controller =
        TextEditingController(text: rep != null ? rep.toString() : "0");

    return Row(
      children: <Widget>[
        Text("Set $index"),
        Flexible(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 40),
            child: TextField(
              onChanged: (text) {
                tempSet[index].rep = num.parse(text).toInt();
                print(tempSet);
              },
              controller: _controller,
              decoration: InputDecoration(
                labelText: "Rep count",
              ),
            ),
          ),
        ),
        IconButton(
          icon: Icon(Icons.delete),
          onPressed: () => _removeSet(index),
        ),
      ],
    );
  }

  List<Widget> _rows() {
    return tempSet.map((s) => _row(s.order, s.rep)).toList();
  }

  void _addSet() {
    if (tempSet.length == 0) {
      tempSet.add(TempSet(0, null, null));
    } else {
      final lastSet = tempSet.last;
      tempSet.add(TempSet(tempSet.indexOf(lastSet) + 1, null, null));
    }
  }

  void _removeSet(int index) {
    setState(() {
      tempSet.removeAt(index);
      _updateIndexes();
    });
  }

  void _updateIndexes() {
    tempSet.asMap().forEach((index, s) {
      s.order = index;
    });
  }

  @override
  void initState() {
    _addSet();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ..._rows(),
        RaisedButton(
          onPressed: () {
            setState(() {
              _addSet();
            });
          },
          child: Text("Add set"),
        )
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您应该避免使用小部件功能。将它们声明为类。