简体   繁体   English

How to create rows data in to DataTable using from json model json api respons flutter

[英]How to create rows data in to DataTable using from json model json api respons flutter

I am tryieng to fetch json data into the Flutter DataTable.我正在尝试将 json 数据提取到 Flutter 数据表中。 Using Api and employee Model.使用 Api 和员工 Model。 I am able to ftech the json data getting from Browser.我能够从浏览器获取 json 数据。 I am unable to fetch rows into DataTable.我无法将行提取到 DataTable 中。 Getting an error below:出现以下错误:

LateInitializationError: Field'emps' has not been initialized.

I am facing an issue that unable to getting the values in to the rows.我面临一个无法将值放入行的问题。 How to call values into the rows.如何将值调用到行中。 Please help me How to do?请帮帮我怎么办?

Below is the json data getting from Browser:以下是从浏览器获取的 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"}]

Below is the API:下面是 API:

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

Future<List> fetchEmployees() async {
  Uri url = Uri.parse(" Link ");
  final response = await http.get(url);
  return employeesFromJson(response.body);
}

Below is employeemodel:下面是员工模型:

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,
      };
}

Below is my example code:下面是我的示例代码:

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

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

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

class _TestPageState extends State<TestPage> {
  late List<Employees> emps;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example'),
      ),
      body: SingleChildScrollView(
        child: DataTable(
          columns: const [
            DataColumn(label: Text('ID')),
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Email')),
          ],
          rows: emps
              .map(
                (emp) => DataRow(cells: [
                  DataCell(
                    Text(emp.id.toString()),
                  ),
                  DataCell(
                    Text(emp.name),
                  ),
                  DataCell(
                    Text(emp.email),
                  ),
                ]),
              )
              .toList(),
        ),
      ),

    );
  }
} 
Future<List<Employee>> fetchResults() async {
    List<Employee> _results = [];
    var url ="---your link----";
    var response = await http.get(url);
    if (response.statusCode == 200) {
      var resultsJson = json.decode(response.body).cast<Map<String,dynamic>>();
      await Future.forEach(resultsJson, (element) {
        _results.add(Employee.fromJson(element));
      });
    }

    return Future.value(_results);
  }



class Employee {
  int? empid;
  String? empname;
  String? empemail;

  Employee({this.empid, this.empname, this.empemail});

  Employee.fromJson(Map<String, dynamic> json) {
    empid = json['empid'];
    empname = json['empname'];
    empemail = json['empemail'];
  }

Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['empid'] = this.empid;
    data['empname'] = this.empname;
    data['empemail'] = this.empemail;
    return data;
  }
}


class _TestPageState extends State<TestPage> {
  late List<Employees> emps;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example'),
      ),
      body: SingleChildScrollView(
        child: FutureBuilder<List<Employee>>(
          initialData: <Employee>[],
          future: fetchResults(),
          builder: (context, snapshot) {
            if (snapshot.hasError ||
                snapshot.data == null ||
                snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator();
            }

            return DataTable(
              columns: const [
                DataColumn(label: Text('ID')),
                DataColumn(label: Text('Name')),
                DataColumn(label: Text('Email')),
              ],
              rows: List.generate(
                snapshot.data!.length,
                (index) {
                  var emp = snapshot.data![index];
                  return DataRow(cells: [
                    DataCell(
                      Text(emp.id.toString()),
                    ),
                    DataCell(
                      Text(emp.name),
                    ),
                    DataCell(
                      Text(emp.email),
                    ),
                  ]);
                },
              ).toList(),
            );
          },
        ),
      ),
    );
  }
}

I got the solution as below: The API is:我得到的解决方案如下: API 是:

Future<List<Employees>> fetchResults() async {
  Uri url = Uri.parse(" Link ");
  var response = await http.get(url);
  var resultsJson = json.decode(response.body).cast<Map<String, dynamic>>();
  List<Employees> emplist = await resultsJson
      .map<Employees>((json) => Employees.fromJson(json))
      .toList();
  return emplist;
}

The Page Example is:页面示例是:

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

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

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            FutureBuilder<List<Employees>>(
              initialData: const <Employees>[],
              future: fetchResults(),
              builder: (context, snapshot) {
                if (snapshot.hasError ||
                    snapshot.data == null ||
                    snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }

                return DataTable(
                  columns: const [
                    DataColumn(label: Text('ID')),
                    DataColumn(label: Text('Name')),
                    DataColumn(label: Text('Email')),
                  ],
                  rows: List.generate(
                    snapshot.data!.length,
                    (index) {
                      var emp = snapshot.data![index];
                      return DataRow(cells: [
                        DataCell(
                          Text(emp.id.toString()),
                        ),
                        DataCell(
                          Text(emp.name),
                        ),
                        DataCell(
                          Text(emp.email),
                        ),
                      ]);
                    },
                  ).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM