Compare Quotes (Flutter)

mail@pastecode.io avatar
unknown
dart
3 years ago
8.5 kB
1
Indexable
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:login_register_home/dart_models/Order.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:login_register_home/dart_models/Quote_Model.dart';

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

  @override
  State<CompareQuotesScreen> createState() => _CompareQuotesScreenState();
}

const QUOTES_URL = "http://localhost:9000/user/quote";

final GlobalKey<SfDataGridState> key = GlobalKey<SfDataGridState>();
final DataGridController _dataGridController = DataGridController();

late Future<List<Quote_Model>> futureQuotes;

@override
void initState() {
  // super.initState();
  futureQuotes = getQuotes();
}

Future<List<Quote_Model>> getQuotes() async {
  final response = await Dio().get(QUOTES_URL);

  if (response.statusCode == 201) {
    // print("This is response.data ${response.data}");

    var convertedData = (response.data as List)
        .map((element) => Quote_Model.fromJson(element))
        .toList();
    // print("Breakpoint");
    // print("This is converted data ${convertedData.forEach((element) {
    //   print(element);
    // })}");
    // convertedData.forEach((element) {
    //   print(element.toString());
    // });
    return convertedData;
  } else {
    throw Exception('Failed to load Quotes');
  }
}

void dispose() {
  _dataGridController.dispose();
}

class _CompareQuotesScreenState extends State<CompareQuotesScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Compare Quotes"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          // crossAxisAlignment: CrossAxisAlignment.center,
          // mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  flex: 1,
                  child: FutureBuilder(
                    future: getQuotesDataSource(),
                    builder: (BuildContext context,
                        AsyncSnapshot<dynamic> snapshot) {
                      print("This is snapshot.data ${snapshot.data}");
                      return snapshot.hasData
                          ? SfDataGrid(
                              showCheckboxColumn: true,
                              checkboxColumnSettings:
                                  const DataGridCheckboxColumnSettings(
                                      showCheckboxOnHeader: false),
                              allowSorting: true,
                              allowTriStateSorting: true,
                              defaultColumnWidth: 130,
                              source: snapshot.data,
                              columns: getColumns(),
                              selectionMode: SelectionMode.single)
                          : const Center(
                              child: CircularProgressIndicator(
                                strokeWidth: 3,
                              ),
                            );
                    },
                  ),
                )
              ],
            ),
            Center(
                child: ElevatedButton(
                    onPressed: () {
                      orderQuotes(_dataGridController.selectedRows);
                    },
                    child: Text("Convert to order")))
          ],
        ),
      ),
    );
  }

  Future<QuotesDataGridSource> getQuotesDataSource() async {
    var quotesList = await getQuotes();
    return QuotesDataGridSource(quotesList);
  }

  List<GridColumn> getColumns() {
    return <GridColumn>[
      GridColumn(
          columnName: 'qrId',
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Request ID"),
          )),
      GridColumn(
          columnName: 'supplierId',
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Supplier Name"),
          )),
      GridColumn(
          columnName: 'itemNames',
          allowSorting: false,
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Items"),
          )),
      GridColumn(
          columnName: 'quantity',
          allowSorting: false,
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Quantity (in units)"),
          )),
      GridColumn(
          columnName: 'tax',
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Tax Included"),
          )),
      GridColumn(
          columnName: 'total',
          label: Container(
            padding: const EdgeInsets.fromLTRB(12, 5, 12, 5),
            alignment: Alignment.center,
            child: const Text("Total Cost (\$)"),
          )),
    ];
  }

  orderQuotes(List<DataGridRow> selectedRows) {}
}

class QuotesDataGridSource extends DataGridSource {
  QuotesDataGridSource(this.quotesList) {
    buildDataGridRow();
  }

  late List<DataGridRow> dataGridRows;
  late List<Quote_Model> quotesList;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(cells: [
      Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[0].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[1].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[2].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[3].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[4].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[5].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
    ]);
  }

  List<DataGridRow> get rows => dataGridRows;

  void buildDataGridRow() {
    dataGridRows = quotesList.map<DataGridRow>((dataGridRow) {
      List<String> itemIdsList = [];
      List<String> quantitiesList = [];
      double tax = 0.05 * dataGridRow.total;
      dataGridRow.items.forEach((element) {
        itemIdsList.add(element.productId);
        quantitiesList.add(element.quantity.toString());
      });

      String itemIds = itemIdsList.join("\n");
      String quantities = quantitiesList.join("\n");

      return DataGridRow(cells: [
        DataGridCell<String>(columnName: 'qrId', value: dataGridRow.qrId),
        DataGridCell<String>(
            columnName: 'supplierId', value: dataGridRow.supplierId),
        DataGridCell<String>(columnName: 'itemIds', value: itemIds.toString()),
        DataGridCell<String>(
            columnName: 'quantity', value: quantities.toString()),
        DataGridCell<double>(columnName: 'tax', value: tax),
        DataGridCell<int>(columnName: 'total', value: dataGridRow.total),
      ]);
    }).toList(growable: false);
  }
}