在Flutter中每行之后打印列标题

k97glaaz  于 2023-03-24  发布在  Flutter
关注(0)|答案(1)|浏览(123)

我正在尝试做一个简单的Flutter应用程序,它从Firebase获取数据并将其显示在DataTable小部件中。我面临的问题是列标题(例如。姓名,电话)在每行之后被“打印”。我希望解决这个问题。下面是我到目前为止的代码。请忽略注解代码。谢谢。

import 'dart:math';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:sub_mgmt/page/addnewpage.dart';
import 'package:sub_mgmt/page/data/users.dart';
import 'package:sub_mgmt/page/model/user.dart';

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

  @override
  State<SortableTable> createState() => _SortableTableState();
}

class _SortableTableState extends State<SortableTable> {
  // Sorting functionalities
  // late List<User> users;
  // int? sortColumnIndex;
  // bool isAscending = false;

  // Reading data from firebase
  CollectionReference _referenceMembers = FirebaseFirestore.instance.collection('users');
  late Stream<QuerySnapshot> _streamMembers;

  @override
  void initState() {
    super.initState();
    // users = List.of(allUsers);
    _streamMembers = _referenceMembers.snapshots();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot>(
        stream: _streamMembers,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text(snapshot.error.toString()));
          }

          if (snapshot.connectionState == ConnectionState.active) {
            QuerySnapshot querySnapshot = snapshot.data;
            List<QueryDocumentSnapshot> listQueryDocumentSnapshot =
                querySnapshot.docs;

            // Original
            return ListView.builder(
                itemCount: listQueryDocumentSnapshot.length,
                itemBuilder: (context, index) {
                  QueryDocumentSnapshot document =
                  listQueryDocumentSnapshot[index];
                  return Member(document: document);
                });
          }
            return Center(child: CircularProgressIndicator());
          }
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) => AddNewPage()));
        },
        tooltip: 'Increment',
        elevation: 4.0,
        child: Icon(Icons.add),
      ),
    );
  }
}

 
class Member extends StatefulWidget {
  const Member({
    Key? key,
    required this.document,
  }) : super(key: key);

  final QueryDocumentSnapshot<Object?> document;

  @override
  State<Member> createState() => MemberState();
}

class MemberState extends State<Member> {

  final columns = ['Name', 'Phone'];
  @override
  Widget build(BuildContext context) {
    return DataTable(
      columns: const [
        DataColumn(label: Text('Name')),
        DataColumn(label: Text('Phone')),
      ],
      rows: [
        DataRow(
            cells: <DataCell>[
              DataCell(Text(widget.document['Name'])),
              DataCell(Text(widget.document['Phone'].toString())),
            ]
        )
      ],
    );
  }
}

现在是这样的

我知道DataTable小部件正在重复构建,但我无法找到解决方法。

kqqjbcuj

kqqjbcuj1#

您迭代ListView中的每个成员,每个成员都有

columns: const [
  DataColumn(label: Text('Name')),
  DataColumn(label: Text('Phone')),
],

为什么不将此DataTable移到ListView之外

DataTable(
  columns: const [
    DataColumn(label: Text('Name')),
    DataColumn(label: Text('Phone')),
  ],
  rows: rows, // Your list of DataRows 
);

并创建DataRow列表,每个DataRow就像一个成员

List<DataRow> get rows => listQueryDocumentSnapshot.map((element) => 
  DataRow(
    cells: <DataCell>[
      DataCell(Text(element['Name'])),
      DataCell(Text(element['Phone'].toString())),
    ]
  )).toList();
  • 我认为你甚至不需要ListView.builder

这就够了

DataTable(
  columns: const [
    DataColumn(label: Text('Name')),
    DataColumn(label: Text('Phone')),
  ],
  rows: listQueryDocumentSnapshot.map((element) => 
    DataRow(
      cells: <DataCell>[
        DataCell(Text(element['Name'])),
        DataCell(Text(element['Phone'].toString())),
      ]
    )).toList();
);

相关问题