Рассчитать общую стоимость флаттера с mysql - PullRequest
0 голосов
/ 04 мая 2020

Эй, ребята, мне нужна помощь. Я не могу рассчитать общую стоимость при оформлении заказа. Я получаю данные с моего mysql сервера. Я уже перепробовал много вещей, но не смог решить эту проблему. Кто-нибудь может мне помочь?
функция returnTotalAmount обернута виджетом BottomBar, это всего лишь пользовательский интерфейс, поэтому я не поделился им.

          home: new Scaffold(
    appBar: new AppBar(title: const Text('MySQL Images Text')),
    body: new Center(
      //FutureBuilder is a widget that builds itself based on the latest snapshot
      // of interaction with a Future.
      child: new FutureBuilder<List<Employee>>(
        future: Services.getEmployees(),
        //we pass a BuildContext and an AsyncSnapshot object which is an
        //Immutable representation of the most recent interaction with
        //an asynchronous computation.
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<Employee> _employee = snapshot.data;
            Services.getEmployees();
            return  Scaffold(
              body: SafeArea(
                child: CustomListView(_employee),
              ),
              bottomNavigationBar: BottomBar(_employee),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }





String returnTotalAmount(List<Employee> _employee) {
double totalAmount = 0.0;

for (int i = 0; i < _employee.length; i++) {
  totalAmount = totalAmount + _employee[i].price * _employee[i].quantity;
}
return totalAmount.toRadixString(2);
}



       Container totalAmount(List<Employee> _employee) {
        return Container(
        margin: EdgeInsets.only(right: 10),
        padding: EdgeInsets.all(25),
        child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
        Text(
         " Total:",
         style: TextStyle(fontSize: 25, fontWeight: FontWeight.w300),
        ),
        Text(
        "\$${returnTotalAmount(_employee)}",
         style: TextStyle(fontWeight: FontWeight.w700, fontSize: 28),
        ),
      ],
    ),
   );
  }

это моя страница оформления заказа, я должен рассчитать цену

enter image description here

this is my Employee Page


  class Employee{
  String id;
   String firstName;
  String price;
  String path;
  String quantity;

   Employee({this.id, this.firstName,this.price,this.path,this.quantity});

  factory Employee.fromjson(Map<String, dynamic> json){
   return Employee(
    id: json['id'] as String,
    firstName: json['first_name'] as String,
    price: json['price'] as String,
    path: json['path'] as String,
    quantity: json['quantity'] as String,
    );
    }}

и это мой код API для получение данных из базы данных

    static Future<List<Employee>> getEmployees() async {
    try {
    var map = Map<String, dynamic>();
    map['action'] = _GET_ALL_ACTION;
    final response = await http.post(ROOT, body: map);
    print('getEmployees Response: ${response.body}');
    if (200 == response.statusCode) {
     List<Employee> list = parseResponse(response.body);
     return list;
    } else {
      return List<Employee>();
    }
  }  catch (e) {
   return List<Employee>(); // return an empty list on exception/error
  }
 }

1 Ответ

0 голосов
/ 09 мая 2020

String returnTotalAmount (List _employee) {double totalAmount = 0.0;

for (int i = 0; i < _employee.length; i++) {
  totalAmount = totalAmount + (double.parse(_employee[i].price)*double.parse(_employee[i].quantity));
}
return totalAmount.toString();

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...