按下按钮删除一行

Delete a row by pressing the button

我想要做的是在 DataTable 行的最后一个单元格中出现一个按钮,当用户单击同一行时,必须删除该按钮。我找不到任何可以帮助我的东西。

import 'package:app/views/login_page.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';

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

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

Future<List> getBookings() async {
  var ref =
      FirebaseDatabase.instance.ref("server/bookings/" + currentCard + "/");
  DataSnapshot event = await ref.get();

  List<DataRow> bookings = [];
  for (var meal in event.children) {
    bookings.add(
      DataRow(
        cells: [
          DataCell(Text(meal.child("data").value.toString())),
          DataCell(Text(meal.child("tipo").value.toString())),
          DataCell(Text(meal.child("local").value.toString())),
          DataCell(IconButton(
            icon: Icon(Icons.delete),
            onPressed: () {
              //Delete row
            },
          )),
        ],
      ),
    );
  }

  print(bookings);
  return bookings;
}

class _ListPageState extends State<ListPage> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Center(
          child: FutureBuilder(
            future: getBookings(),
            builder: (context, snapshot) {
              return DataTable(
                  showCheckboxColumn: true,
                  columns: const [
                    DataColumn(label: Text("Data")),
                    DataColumn(label: Text("Tipo")),
                    DataColumn(label: Text("Local")),
                    DataColumn(label: Text("")),
                  ],
                  rows: snapshot.data as List<DataRow>);
            },
          ),
        ),
      ],
    );
  }
}

对我来说最大的困难是获取点击行的索引以便能够删除它

您的方法的主要问题是访问和更改您在未来获得的数据。

此代码在最小示例中显示了问题:

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

  @override
  State<ExampleWidget> createState() => _ExampleWidgetState();

  Future<List<Text>> getData() async {
    return [Text('1'), Text('2')];
  }
}

class _ExampleWidgetState extends State<ExampleWidget> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Text>>(
        future: widget.getData(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return Container();
          return Column(children: snapshot.data!);
        });
  }
}

如您所见,之后无法编辑列表。为了使其可访问,需要将其添加到小部件的状态。这里最简单的方法就是将您的响应保存为您所在州的一个字段,并在您所在州的“构建”方法中构建小部件。举个例子:

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

  @override
  State<ExampleWidget2> createState() => _ExampleWidgetState2();
}

class _ExampleWidgetState2 extends State<ExampleWidget2> {
  List<String>? _data;

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

  Future getData() async {
    _data = ['1', '2'];
  }

  @override
  Widget build(BuildContext context) {
    if (_data == null) {
      return Container();
    } else {
      List<Widget> widgets = [];

      for (String item in _data!) {
        widgets.add(ElevatedButton(
             onPressed: () {
              setState(() {
                _data!.remove(item);
              });
            },
            child: Text(item)));
      }

      return Column(children: widgets);
    }
  }
}

如您所见,我在第二个示例中添加了按钮,通过操作状态变量和设置状态来删除点击时的行。