Продолжаю разбираться с локализацией
This commit is contained in:
237
lib/purchase.dart
Normal file
237
lib/purchase.dart
Normal file
@@ -0,0 +1,237 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'dart:convert';
|
||||
import 'dart:core';
|
||||
|
||||
import 'package:checker/strings.dart';
|
||||
import 'package:checker/common.dart';
|
||||
import 'package:checker/consts.dart';
|
||||
import 'package:checker/network.dart';
|
||||
import 'package:checker/base_state.dart';
|
||||
import 'package:checker/purchase_success.dart';
|
||||
|
||||
/// Экран проведения покупки.
|
||||
class PurchaseScreen extends StatefulWidget {
|
||||
|
||||
PurchaseScreen(this.user, this.card);
|
||||
|
||||
final String user;
|
||||
final String card;
|
||||
|
||||
@override State createState() => new PurchaseScreenState<PurchaseScreen>(user, card);
|
||||
}
|
||||
|
||||
class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
|
||||
|
||||
/// Объект, помогающий вручную изменять введенный пользователем текст.
|
||||
/// Используется для форматирования введенных пользователем данных
|
||||
/// (удаляет запрещенные символы до их отображаения).
|
||||
TextEditingController controller = new TextEditingController();
|
||||
|
||||
PurchaseScreenState(String userString, String card) {
|
||||
this.user = JSON.decode(userString);
|
||||
this.card = card;
|
||||
getLoyality(user['loyalty_url']);
|
||||
}
|
||||
|
||||
bool purchaseInProgress = false;
|
||||
Map user;
|
||||
String card = '';
|
||||
String loyality = '';
|
||||
|
||||
@override Widget getScreenContent() {
|
||||
return new Column(
|
||||
children: <Widget>[new Expanded(child: new ListView(children: <Widget>[
|
||||
getValueWithDescription(Strings.of(context).userName(), user['first_name'] == null ? '' : user['first_name']),
|
||||
getValueWithDescription(Strings.of(context).card(), card),
|
||||
getValueWithDescription(Strings.of(context).reward(), loyality),
|
||||
getHintLabel(),
|
||||
getInputField(),
|
||||
buildButton(getScreenMargins(36.0), getCompleteButton()),
|
||||
buildButton(getScreenMargins(24.0), getScanButton(context, Strings.of(context).scan(), primaryColor))
|
||||
]))]);
|
||||
}
|
||||
|
||||
getScreenMargins(double top) {
|
||||
double side = 42.0;
|
||||
return new EdgeInsets.only(top: top, left: side, right: side);
|
||||
}
|
||||
|
||||
getCompleteButton() {
|
||||
String title = Strings.of(context).completePurchase();
|
||||
return buildRaisedButton(context, title, () => onPurchaseClick(context));
|
||||
}
|
||||
|
||||
Widget getScanButton(BuildContext context, String title, Color textColor) {
|
||||
return new Container(height: buttonHeight, child: new FlatButton(child: new Text(title,
|
||||
style: new TextStyle(color: textColor)),
|
||||
onPressed: () => startScanner(context)),
|
||||
decoration: getDecorationForScanButton());
|
||||
}
|
||||
|
||||
getDecorationForScanButton() {
|
||||
return new BoxDecoration(
|
||||
border: new Border.all(color: primaryColor, width: 1.0),
|
||||
borderRadius: new BorderRadius.all(new Radius.circular(4.0)));
|
||||
}
|
||||
|
||||
@override String getTitle() {
|
||||
return Strings.of(context).carryingPurchase();
|
||||
}
|
||||
|
||||
@override getHint() {
|
||||
return Strings.of(context).sum();
|
||||
}
|
||||
|
||||
@override getMenuButtons(BuildContext context) {
|
||||
return <Widget>[getFaqButton(), getLogoutButton()];
|
||||
}
|
||||
|
||||
@override Color getTextFilledBackground() {
|
||||
return Colors.white;
|
||||
}
|
||||
|
||||
@override getTextWidget() {
|
||||
return new TextField(
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: new InputDecoration.collapsed(
|
||||
hintText: getHint(),
|
||||
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)
|
||||
),
|
||||
controller: controller,
|
||||
onSubmitted: (String text) {
|
||||
setState(() {
|
||||
controller.text = _parseSum(text);
|
||||
});
|
||||
},
|
||||
textAlign: TextAlign.center,
|
||||
autofocus: true,
|
||||
);
|
||||
}
|
||||
|
||||
getLoyality(String url) async {
|
||||
|
||||
if (await platform.invokeMethod('isOnline')) {
|
||||
|
||||
var headers = {
|
||||
'DM-Authorization': 'dmapptoken $appToken',
|
||||
'Authorization': 'dmtoken ${token}'
|
||||
};
|
||||
|
||||
httpClient.get(url, headers: headers).then((response) {
|
||||
|
||||
print(response.body);
|
||||
|
||||
Map bonuses = JSON.decode(response.body);
|
||||
String type = bonuses['type'];
|
||||
setState(() {
|
||||
if (type == 'amount') {
|
||||
this.loyality = '${user['discount']}%';
|
||||
} else {
|
||||
List amountToBonus = bonuses['amount_to_bonus'];
|
||||
double loyalityVal = (double.parse(amountToBonus[1]) / amountToBonus[0]) * 100;
|
||||
this.loyality = '${loyalityVal.toStringAsFixed(0)}%';
|
||||
}
|
||||
});
|
||||
}).catchError((error) {
|
||||
print(error.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
String _cleanupNumber(String text){
|
||||
String tmp = text
|
||||
.replaceAll(' ', '')
|
||||
.replaceAll('-', '')
|
||||
.replaceAll(',', '.')
|
||||
.replaceAll('..', '.');
|
||||
|
||||
while(tmp.indexOf('..') != -1){
|
||||
tmp = tmp.replaceAll('..', '.');
|
||||
}
|
||||
return tmp;
|
||||
}
|
||||
|
||||
_parseSum(String input) {
|
||||
num sumTotal = 0.0;
|
||||
String text = _cleanupNumber(input);
|
||||
|
||||
try {
|
||||
sumTotal = num.parse(text);
|
||||
} catch(exception) {
|
||||
print(exception);
|
||||
try {
|
||||
int idx = text.indexOf('.');
|
||||
String integerPart = text.substring(0, idx);
|
||||
String fractionalPart = text.substring(idx + 1, text.length);
|
||||
if(fractionalPart.length > 2) {
|
||||
fractionalPart = fractionalPart.substring(0, 2);
|
||||
}
|
||||
return '${integerPart}.${fractionalPart}';
|
||||
} catch(exception){
|
||||
print(exception);
|
||||
}
|
||||
}
|
||||
return sumTotal.toStringAsFixed(2);
|
||||
}
|
||||
|
||||
onPurchaseClick(BuildContext context) {
|
||||
String val = _parseSum(controller.text);
|
||||
showDialog(context: context, child: new AlertDialog(
|
||||
title: new Text(Strings.of(context).confirmation()),
|
||||
content: new Text(getContentMessage(val)),
|
||||
actions: <Widget>[
|
||||
new FlatButton(
|
||||
child: new Text(Strings.of(context).no()),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
new FlatButton(
|
||||
child: new Text(Strings.of(context).yes()),
|
||||
onPressed: () {
|
||||
purchase(val);
|
||||
},
|
||||
)
|
||||
]));
|
||||
}
|
||||
|
||||
getContentMessage(String val) {
|
||||
return Strings.of(context).confirmPurchase();
|
||||
}
|
||||
|
||||
purchase(String sumTotal) async {
|
||||
if (await platform.invokeMethod('isOnline')) {
|
||||
if (!purchaseInProgress) {
|
||||
purchaseInProgress = true;
|
||||
platform.invokeMethod('getDocID').then((result) {
|
||||
|
||||
String url = user['purchases_url'];
|
||||
|
||||
var body = {
|
||||
'doc_id': result,
|
||||
'curr_iso_code': '643',
|
||||
'commit': 'true',
|
||||
'sum_total': sumTotal
|
||||
};
|
||||
|
||||
var headers = {
|
||||
'DM-Authorization': 'dmapptoken $appToken',
|
||||
'Authorization': 'dmtoken ${token}'
|
||||
};
|
||||
|
||||
httpClient.post(url, body: body, headers: headers).then((response) {
|
||||
|
||||
print(response.body);
|
||||
Navigator.of(context).pop();
|
||||
pushRoute(context, new PurchaseSuccessScreen(sumTotal, user['first_name'] == null ? '' : user['first_name']));
|
||||
|
||||
}).catchError((error) {
|
||||
purchaseInProgress = false;
|
||||
print(error.toString());
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user