android - 从动态数据表 flutter 中获取选定的行索引

标签 android flutter dart datatables flutter-layout

在 flutter 中,我有动态小部件数据表。使用按钮在提交值(通过edittextbox)时添加行。在行字段中添加和删除行(在单击特定行时)。下面的代码给了我从列表中删除最后一行的输出。我需要从表中删除我单击/选择的行。它应该找到该行的索引以删除该行。有没有其他方法可以达到预期的效果? 我正在使用 List<DataRow> row =[];

 Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
       FlatButton.icon(
      color: Colors.orange,
      icon: Icon(FontAwesomeIcons.shoppingBag),
      label: Text('Add to List'), 

      onPressed: () async{
        ttl = int.parse(rate) * int.parse(noInputController.text);

         setState(() {

         this.row.add(
           new DataRow(
        cells: [
          DataCell( Icon(Icons.remove_circle, color: Colors.red,),
            //Text('remove', style: TextStyle(color: Colors.blue,decoration: TextDecoration.underline,),

        onTap: () {
       setState(() {
        //remove  item
        if(amt > 0){
        amt = amt - ttl;
        }
        print(amt);
        if (index  != -1){
        print("before: $index $rowindex");
       rowindex.removeAt(index);
       //row.removeAt(index);
       index = index - 1;
       print("after: $index $rowindex");
        }else{
          print('no rows');
        }

       });
      }),
        DataCell(Text(prd),
        onTap: () {
       setState(() {

       });
      }),
      DataCell(Text(noInputController.text),
      onTap: () {
      setState(() {

       });
      }),
      DataCell(Text(rate),
        onTap: () {
        setState(() {

       });
      }),
       DataCell(Text(ttl.toString()),
        onTap: () {
        setState(() {

       });
      }),
      DataCell(Text(stype),
        onTap: () {
        setState(() {

       });
      }),
        ]));
           print("before: $index $rowindex");
           index = index + 1;
            this.rowindex.add(index);
            print("after: $index $rowindex");
       // print(this.row.length);
         return this.row;
         });

         rstitem();  //get total
                }
    ),]),
        SizedBox(
          height: ScreenUtil.getInstance().setHeight(20),
        ),



         new SingleChildScrollView(
          scrollDirection: Axis.horizontal,
            child: DataTable(
  columns: [
    DataColumn(label: Text("Remove",style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0,color: Colors.blue))),
    DataColumn(  //tooltip: "item code for products",
          label: Text("Name",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15.0,color: Colors.blue))),
        DataColumn(label: Text("Quantity",style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0,color: Colors.blue))),
        DataColumn(label: Text("Rate",style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0,color: Colors.blue))),
        DataColumn(label: Text("Total",style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0,color: Colors.blue))),
        DataColumn(label: Text("Item Type",style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15.0,color: Colors.blue)))
  ],
  rows: row,
),),

帮我解决这个问题。

最佳答案

删除数据时,请删除模型列表中的数据
代码 fragment

deleteSelected() async {
    setState(() {
      if (selectedUsers.isNotEmpty) {
        List<User> temp = [];
        temp.addAll(selectedUsers);
        for (User user in temp) {
          users.remove(user);
          selectedUsers.remove(user);
        }
      }
    });
  }

并且在行属性中使用 map

rows: users
            .map(
              (user) => DataRow(
              selected: selectedUsers.contains(user),
              onSelectChanged: (b) {
                print("Onselect");
                onSelectedRow(b, user);
              }

完整代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: DataTableDemo(),
    );
  }
}



class User {
  String firstName;
  String lastName;

  User({this.firstName, this.lastName});

  static List<User> getUsers() {
    return <User>[
      User(firstName: "Aaryan", lastName: "Shah"),
      User(firstName: "Ben", lastName: "John"),
      User(firstName: "Carrie", lastName: "Brown"),
      User(firstName: "Deep", lastName: "Sen"),
      User(firstName: "Emily", lastName: "Jane"),
    ];
  }
}

class DataTableDemo extends StatefulWidget {
  DataTableDemo() : super();

  final String title = "Data Table Flutter Demo";

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

class DataTableDemoState extends State<DataTableDemo> {
  List<User> users;
  List<User> selectedUsers;
  bool sort;

  @override
  void initState() {
    sort = false;
    selectedUsers = [];
    users = User.getUsers();
    super.initState();
  }

  onSortColum(int columnIndex, bool ascending) {
    if (columnIndex == 0) {
      if (ascending) {
        users.sort((a, b) => a.firstName.compareTo(b.firstName));
      } else {
        users.sort((a, b) => b.firstName.compareTo(a.firstName));
      }
    }
  }

  onSelectedRow(bool selected, User user) async {
    setState(() {
      if (selected) {
        selectedUsers.add(user);
      } else {
        selectedUsers.remove(user);
      }
    });
  }

  deleteSelected() async {
    setState(() {
      if (selectedUsers.isNotEmpty) {
        List<User> temp = [];
        temp.addAll(selectedUsers);
        for (User user in temp) {
          users.remove(user);
          selectedUsers.remove(user);
        }
      }
    });
  }

  SingleChildScrollView dataBody() {
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: DataTable(
        sortAscending: sort,
        sortColumnIndex: 0,
        columns: [
          DataColumn(
              label: Text("FIRST NAME"),
              numeric: false,
              tooltip: "This is First Name",
              onSort: (columnIndex, ascending) {
                setState(() {
                  sort = !sort;
                });
                onSortColum(columnIndex, ascending);
              }),
          DataColumn(
            label: Text("LAST NAME"),
            numeric: false,
            tooltip: "This is Last Name",
          ),
        ],
        rows: users
            .map(
              (user) => DataRow(
              selected: selectedUsers.contains(user),
              onSelectChanged: (b) {
                print("Onselect");
                onSelectedRow(b, user);
              },
              cells: [
                DataCell(
                  Text(user.firstName),
                  onTap: () {
                    print('Selected ${user.firstName}');
                  },
                ),
                DataCell(
                  Text(user.lastName),
                ),
              ]),
        )
            .toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        verticalDirection: VerticalDirection.down,
        children: <Widget>[
          Expanded(
            child: dataBody(),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20.0),
                child: OutlineButton(
                  child: Text('SELECTED ${selectedUsers.length}'),
                  onPressed: () {},
                ),
              ),
              Padding(
                padding: EdgeInsets.all(20.0),
                child: OutlineButton(
                  child: Text('DELETE SELECTED'),
                  onPressed: selectedUsers.isEmpty
                      ? null
                      : () {
                    deleteSelected();
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

enter image description here

关于android - 从动态数据表 flutter 中获取选定的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58451457/

相关文章:

flutter - Flutter StreamBuilder从先前的生成器流中生成快照

soap - 如何在 Dart 上生成摘要密码以与 ip camera 通信

java - 如何结合Recyclerview和Fragment?

android - 如何在一个 LinearLayout 内的多个图像上设置文本?

macos - SocketException : Connection failed (OS Error: Operation not permitted, errno = 1) 在 macOS 上使用 flutter 应用程序

flutter - 为什么调用非空 setState()?

android - 如何在 appcompat.v7 中获取主页 View

android - 将 XLS (Excel) 文件附加到电子邮件

flutter - 如何截取当前小部件的屏幕截图 - Flutter

flutter - Flutter:将导航功能与没有命名路线的MaterialPageRoute一起用于命名路线