0

我正在使用 Mysql 数据库作为 Flutter Web App 的后端。我创建了 api 和模型来从 mysql 获取数据。我能够以 Json 格式获取表数据。我能够 ftech 从浏览器获取的 json 数据。我想将这些数据提取到颤振 Web 应用程序上的 paginatedDataTable 中。我面临的问题是如何将这些数据转换为分页数据表。请帮助我如何做到这一点。如何在 Flutter Web 应用程序上将 json 数据提取到 paginatedDataTable 中。

以下是从浏览器获取的 json 数据:

[{"empid":1,"empname":"empname","empemail":"email1"},{"empid":2,"empname":"name2","empemail":"email2"},{"empid":3,"empname":"t1","empemail":"e1"},{"empid":7,"empname":"t2","empemail":"e2"}]

以下是 API:

import 'package:http/http.dart' as http;

import 'employees_model.dart';

Future<List> fetchEmployees() async {
  Uri url = Uri.parse("http://localhost:3000/employees_router/all");
  final response = await http.get(url);
  return employeesFromJson(response.body);
}

下面是员工模型:

import 'dart:convert';

List<Employees> employeesFromJson(String str) =>
    List<Employees>.from(json.decode(str).map((x) => Employees.fromJson(x)));

String employeesToJson(List<Employees> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Employees {
  Employees({
    required this.id,
    required this.name,
    required this.email,
  });

  int id;
  String name;
  String email;

  factory Employees.fromJson(Map<String, dynamic> json) => Employees(
        id: json["empid"],
        name: json["empname"],
        email: json["empemail"],
      );

  Map<String, dynamic> toJson() => {
        "empid": id,
        "empname": name,
        "empemail": email,
      };
}

下面是我不完整的带有分页数据表的示例代码:

import 'package:flutter/material.dart';
import 'package:webappmysql/employees_model.dart';
import 'package:webappmysql/employees_api.dart';

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

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

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Example'),
      ),
      body: Container(
        padding: const EdgeInsets.all(16.0),
        child: FutureBuilder(
          future: fetchEmployees(),
          builder: (BuildContext ctx, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.length,
                //shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) {
                  Employees employee = snapshot.data[index];
                  ////return Text(user.title);
                  return PaginatedDataTable(
                    source: _dataSource,
                    
                    header: const Text('Employees'),
                    columns: const [
                      DataColumn(label: Text('ID')),
                      DataColumn(label: Text('Name')),
                      DataColumn(label: Text('Email')),
                    ],
                    columnSpacing: 100,
                    horizontalMargin: 10,
                    rowsPerPage: 8,
                    showCheckboxColumn: false,
                  );
                  // return ListTile(
                  //   title: Text(employee.id.toString()),
                  //   subtitle: Text(employee.name),
                  //   contentPadding: const EdgeInsets.only(bottom: 20.0),
                  // );
                },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            // By default, show a loading spinner.
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
4

1 回答 1

1

改变你HomePage的这个。

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

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

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Example'),
      ),
      body: FutureBuilder(
        future: fetchEmployees(),
        builder: (BuildContext ctx, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: PaginatedDataTable(
                source: dataSource(snapshot.data),
                header: const Text('Employees'),
                columns: const [
                  DataColumn(label: Text('ID')),
                  DataColumn(label: Text('Name')),
                  DataColumn(label: Text('Email')),
                ],
                showCheckboxColumn: false,
              ),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }

          // By default, show a loading spinner.
          return const CircularProgressIndicator();
        },
      ),
    );
  }

  DataTableSource dataSource(List<Employees> employeesList) =>
      MyData(dataList: employeesList);
}

class MyData extends DataTableSource {
  MyData({required this.dataList});
  final List<Employees> dataList;
  // Generate some made-up data

  @override
  bool get isRowCountApproximate => false;
  @override
  int get rowCount => dataList.length;
  @override
  int get selectedRowCount => 0;
  @override
  DataRow getRow(int index) {
    return DataRow(
      cells: [
        DataCell(
          Text(dataList[index].id.toString()),
        ),
        DataCell(
          Text(dataList[index].name),
        ),
        DataCell(
          Text(dataList[index].email),
        ),
      ],
    );
  }
}
于 2022-01-27T20:19:52.197 回答