Локаль можно задать на этапе сборки

This commit is contained in:
Ivan Murashov
2017-09-06 14:01:12 +03:00
parent 3bd9eb4d91
commit 60090ea437
25 changed files with 226 additions and 385 deletions

View File

@@ -18,28 +18,26 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
/// Введенное пользователем значение.
String textFieldValue = '';
Strings s;
@override Widget build(BuildContext ctx) {
return new Scaffold(appBar: getAppBar(ctx),
return new Scaffold(appBar: getAppBar(),
body: new Stack(children: <Widget>[
getScreenContent(ctx),
getScreenContent(),
new Center(child: loading ? new CircularProgressIndicator() : null)
]));
}
/// Возвращает контейнер с всеми виджетами экрана.
Widget getScreenContent(BuildContext ctx);
Widget getScreenContent();
/// Возвращает заголовок для AppBar
String getTitle(BuildContext ctx);
String getTitle();
AppBar getAppBar(BuildContext ctx) {
return new AppBar(title: new Text(getTitle(ctx), style: new TextStyle(fontSize: 18.0)),
backgroundColor: primaryColor, actions: getMenuButtons(ctx));
AppBar getAppBar() {
return new AppBar(title: new Text(getTitle(), style: new TextStyle(fontSize: 18.0)),
backgroundColor: primaryColor, actions: getMenuButtons());
}
List<Widget> getMenuButtons(BuildContext context) {
List<Widget> getMenuButtons() {
return <Widget>[getFaqButton()];
}
@@ -52,28 +50,28 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
}
/// Возврвщает контейнер, внутри которого Text с подсказкой.
Widget getHintLabel(BuildContext ctx) {
Widget getHintLabel() {
double horizontalMargin = 8.0;
return new Container(margin: new EdgeInsets.only(top: horizontalMargin, bottom: horizontalMargin, left: verticalMargin, right: verticalMargin),
child: new Row(crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[new Text(getHintString(ctx), textAlign: TextAlign.left,
children: <Widget>[new Text(getHintString(), textAlign: TextAlign.left,
style: new TextStyle(fontWeight: FontWeight.w300, color: error == null ? greyTextColor : primaryColor, fontSize: 14.0))]));
}
/// Возвращает подсказку, либо ошибку, если введенные в поле ввода данные неверны.
String getHintString(BuildContext ctx) {
String getHintString() {
if (textFieldValue.length == 0 && error == null) {
return ' ';
} else if (error != null) {
return error;
} else {
return getHint(ctx);
return getHint();
}
}
/// Возвращает текст подсказки для поля ввода.
/// Должен быть переопределен на экранах, на которых есть поле ввода.
String getHint(BuildContext ctx) {
String getHint() {
return null;
}
@@ -85,14 +83,17 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
}
/// Метод возвращает контейнер с полем ввода внутри.
Widget getInputField(BuildContext ctx) {
Widget getInputField() {
return new Container(margin: new EdgeInsets.only(left: verticalMargin, right: verticalMargin),
padding: getInputFieldContainerPadding(),
decoration: getInputFieldContainerDecoration(),
child: new TextField(keyboardType: TextInputType.number,
decoration: new InputDecoration.collapsed(hintText: getHint(ctx),
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
onChanged: (text) => handleUserInput(text)));
child: getTextWidget());
}
/// Возвращает поле ввода.
/// Переопределяется для использования на экранах регистрации и проведения покупки.
Widget getTextWidget() {
return null;
}
/// Возвращат паддинги для поля ввода.
@@ -113,7 +114,7 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
}
/// Возвращает выпуклую залитую фирменным цветом кнопку
Widget buildRaisedButton(BuildContext context, String text, VoidCallback onPressed) {
Widget buildRaisedButton(String text, VoidCallback onPressed) {
return new RaisedButton(child: new Text(text,
style: new TextStyle(color: Colors.white)),
onPressed: onPressed,
@@ -138,7 +139,7 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
/// Возвращает список, единственный элемент которого - Text с заголовком для текстового поля.
List<Widget> getDescriptionWidget(String title) {
return <Widget>[new Text(title, textAlign: TextAlign.left, style: new TextStyle(color: greyTextColor, fontSize: 14.0))]
return <Widget>[new Text(title, textAlign: TextAlign.left, style: new TextStyle(color: greyTextColor, fontSize: 14.0))];
}
/// Возвращает список, единственный элемент которого - Text с информацией (размер скидки, сумма проведенной покупки).
@@ -147,7 +148,7 @@ abstract class BaseState<T extends StatefulWidget> extends State<T> {
}
/// Возвращает кнопку, обернутую набором специфичных контейнеров.
Widget buildButton(EdgeInsets margin, Widget widget) {
Widget wrapButton(EdgeInsets margin, Widget widget) {
return new Container(margin: margin, height: buttonHeight, child: new Row(children: <Widget>[new Expanded(child: widget)]));
}

View File

@@ -11,9 +11,6 @@ import 'strings.dart';
// Канал для взаимодействия с кодом платформы.
const platform = const MethodChannel('com.dinect.checker/instance_id');
/// Токен кассы. Инициализируется при регистрации.
String token;
// Метод обеспечивает замену текущего объекта route новым.
pushRoute(BuildContext context, Widget widget) {
var route = new MaterialPageRoute<Null>(builder: (BuildContext context) => widget);
@@ -27,8 +24,8 @@ faq(BuildContext context, bool returnToScanner) {
}
// В методе отправляется запрос на удаление токена кассы, очищаются SharedPreferences приложения.
logout(BuildContext context) {
logout(BuildContext context) async {
String token = await platform.invokeMethod('getToken');
VoidCallback positiveCalback = () {
if (token != null) {
deleteToken(token).then((response) {
@@ -47,11 +44,11 @@ logout(BuildContext context) {
}
};
showYesNoDialog(context, Strings.of(context).confirmation(), Strings.of(context).askChangeStore(), positiveCalback);
showYesNoDialog(context, StringsLocalization.confirmation(), StringsLocalization.askChangeStore(), positiveCalback);
}
forceLogout(BuildContext context) {
forceLogout(BuildContext context) async {
String token = await platform.invokeMethod('getToken');
deleteToken(token).then((response) {
print(response.body);
platform.invokeMethod('removeKeys').then((result) {
@@ -67,6 +64,7 @@ forceLogout(BuildContext context) {
/// Может производиться с нескольких экранов (splash, finish_registration).
startScanner(BuildContext context) async {
String token = await platform.invokeMethod('getToken');
// Канал ловит вызовы методов из "нативной" части приложения.
// Могут быть вызваны либо logaut либо faq, либо purchase.
if (token != null) {
@@ -101,12 +99,12 @@ showYesNoDialog(BuildContext context, String title, String content, VoidCallback
content: new Text(content),
actions: <Widget>[
new FlatButton(
child: new Text(Strings.of(context).no()),
child: new Text(StringsLocalization.no()),
onPressed: () {
Navigator.of(context).pop();
}
),
new FlatButton(
child: new Text(Strings.of(context).yes()),
child: new Text(StringsLocalization.yes()),
onPressed: positiveCallback)]));
}

View File

@@ -51,7 +51,7 @@ class FAQScreenState<T> extends BaseState<FAQScreen> {
return "FAQ";
}
@override getMenuButtons(BuildContext context) {
@override getMenuButtons() {
return <Widget>[getLogoutButton()];
}

View File

@@ -24,11 +24,11 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
}
@override String getTitle() {
return Strings.of(context).registration();
return StringsLocalization.registration();
}
@override getHint() {
return Strings.of(context).idStore();
return StringsLocalization.idStore();
}
@override Widget getScreenContent() {
@@ -37,9 +37,9 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
getHintLabel(),
getInputField(),
getMessage(),
buildRaisedButton(context, _tokenActive
? Strings.of(context).completeRegistration()
: Strings.of(context).refreshActivationStatus(), () => handleTap())
buildRaisedButton(_tokenActive
? StringsLocalization.completeRegistration()
: StringsLocalization.refreshActivationStatus(), () => handleTap())
]);
}
@@ -50,6 +50,7 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
startScanner(context);
} else {
if (await platform.invokeMethod('isOnline')) {
String token = await platform.invokeMethod('getToken');
checkTokenStatus(token).then((response) {
print(response.body);
@@ -68,8 +69,9 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
}
}
@override Widget getTextWidget() {
return new Row(children: <Widget>[new Text(_merchantID != null ? _merchantID : '', style: new TextStyle(color: Colors.black, fontSize: 16.0))]);
@override getTextWidget() {
return new Row(children: <Widget>[new Text(_merchantID != null ? _merchantID : '',
style: new TextStyle(color: Colors.black, fontSize: 16.0))]);
}
/// Достаем сохраненный в SharedPreferences merchantID.
@@ -84,7 +86,7 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
/// Метод возвращает контейнер с текстом сообщения и бэкграундом.
getMessage() {
return new Container(height: _tokenActive ? 72.0 : 108.0, decoration: _getDecoraionForMessageField(),
return new Container(height: _tokenActive ? 72.0 : 108.0, decoration: _getDecorationForMessageField(),
margin: new EdgeInsets.only(top: 20.0, left: 12.0, right: 12.0),
padding: new EdgeInsets.only(bottom: 22.0, left: 14.0, right: 14.0),
child: new Center(child: getMessageTextWidget()));
@@ -100,13 +102,14 @@ class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
/// Получаем текст сообщения, в зависимости от статуса активации.
getMessageString() {
return _tokenActive
? Strings.of(context).completeRegistration()
: Strings.of(context).refreshActivationStatus();
? StringsLocalization.completeRegistration()
: StringsLocalization.refreshActivationStatus();
}
/// Фоновое изображение для сообщения.
Decoration _getDecoraionForMessageField() {
Decoration _getDecorationForMessageField() {
return new BoxDecoration(image: new DecorationImage(
image: new ExactAssetImage(_tokenActive ? active_token_bg_png : activate_token_bg_png), fit: _tokenActive ? BoxFit.fitWidth : BoxFit.fill));
image: new ExactAssetImage(_tokenActive ? active_token_bg_png : activate_token_bg_png),
fit: _tokenActive ? BoxFit.fitWidth : BoxFit.fill));
}
}

View File

@@ -16,7 +16,7 @@ class MessageLookup extends MessageLookupByLibrary {
final messages = _notInlinedMessages(_notInlinedMessages);
static _notInlinedMessages(_) => {
"ID_Store" : MessageLookupByLibrary.simpleMessage("DIN Store"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Identifier N is not found"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Identifier %s is not found"),
"app_activ" : MessageLookupByLibrary.simpleMessage("The application is activated"),
"ask_change_store" : MessageLookupByLibrary.simpleMessage("Do you really want to log out and enter a different store number?"),
"buyer" : MessageLookupByLibrary.simpleMessage("Buyer"),

View File

@@ -16,7 +16,7 @@ class MessageLookup extends MessageLookupByLibrary {
final messages = _notInlinedMessages(_notInlinedMessages);
static _notInlinedMessages(_) => {
"ID_Store" : MessageLookupByLibrary.simpleMessage("DIN del negocio "),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("ID N no está encontrado"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("ID %s no está encontrado"),
"app_activ" : MessageLookupByLibrary.simpleMessage("Aplicación está activada"),
"ask_change_store" : MessageLookupByLibrary.simpleMessage("¿Os realmente quiereis acabarse una sesión y dar otro DIN del negocio?"),
"buyer" : MessageLookupByLibrary.simpleMessage("El comprador"),

View File

@@ -16,7 +16,7 @@ class MessageLookup extends MessageLookupByLibrary {
final messages = _notInlinedMessages(_notInlinedMessages);
static _notInlinedMessages(_) => {
"ID_Store" : MessageLookupByLibrary.simpleMessage("DIN магазина"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Идентификатор N не найден"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Идентификатор %s не найден"),
"app_activ" : MessageLookupByLibrary.simpleMessage("Приложение активировано"),
"ask_change_store" : MessageLookupByLibrary.simpleMessage("Вы действительно хотите выйти и ввести другой номер магазина?"),
"buyer" : MessageLookupByLibrary.simpleMessage("Покупатель"),

View File

@@ -16,7 +16,7 @@ class MessageLookup extends MessageLookupByLibrary {
final messages = _notInlinedMessages(_notInlinedMessages);
static _notInlinedMessages(_) => {
"ID_Store" : MessageLookupByLibrary.simpleMessage("DIN магазину"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Ідентифікатор N не знайден"),
"ID_not_found" : MessageLookupByLibrary.simpleMessage("Ідентифікатор %s не знайден"),
"app_activ" : MessageLookupByLibrary.simpleMessage("Додаток активований"),
"ask_change_store" : MessageLookupByLibrary.simpleMessage("Ви дійсно хочете вийти і ввести інший номер магазину"),
"buyer" : MessageLookupByLibrary.simpleMessage("Покупець"),

View File

@@ -2,8 +2,23 @@ import 'package:flutter/material.dart';
import 'splash.dart';
import 'consts.dart';
import 'strings.dart';
import 'common.dart';
import 'dart:async';
class StringsLocalizationDelegate extends LocalizationsDelegate<StringsLocalization> {
@override
Future<StringsLocalization> load(Locale locale) async {
return StringsLocalization.load(await platform.invokeMethod("getLocale"));
}
@override
bool shouldReload(LocalizationsDelegate<StringsLocalization> old) {
return false;
}
}
/// Точка входа в приложение.
void main() {
runApp(new Checker());
@@ -18,7 +33,12 @@ class CheckerState extends State<Checker> {
@override Widget build(BuildContext context) {
return new MaterialApp(
title: appName,
home: new SplashScreen()
home: new SplashScreen(),
localizationsDelegates: getLocalizationsDelegate()
);
}
getLocalizationsDelegate() {
return <StringsLocalizationDelegate>[new StringsLocalizationDelegate()];
}
}

View File

@@ -31,24 +31,24 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
PurchaseScreenState(String userString, String card) {
this.user = JSON.decode(userString);
this.card = card;
getLoyality(user['loyalty_url']);
getLoyalty(user['loyalty_url']);
}
bool purchaseInProgress = false;
Map user;
String card = '';
String loyality = '';
String loyalty = '';
@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),
getValueWithDescription(StringsLocalization.userName(), user['first_name'] == null ? '' : user['first_name']),
getValueWithDescription(StringsLocalization.card(), card),
getValueWithDescription(StringsLocalization.reward(), loyalty),
getHintLabel(),
getInputField(),
buildButton(getScreenMargins(36.0), getCompleteButton()),
buildButton(getScreenMargins(24.0), getScanButton(context, Strings.of(context).scan(), primaryColor))
wrapButton(getScreenMargins(36.0), getCompleteButton()),
wrapButton(getScreenMargins(24.0), getScanButton(context, StringsLocalization.scan(), primaryColor))
]))]);
}
@@ -58,8 +58,7 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
}
getCompleteButton() {
String title = Strings.of(context).completePurchase();
return buildRaisedButton(context, title, () => onPurchaseClick(context));
return buildRaisedButton(StringsLocalization.completePurchase(), () => onPurchaseClick());
}
Widget getScanButton(BuildContext context, String title, Color textColor) {
@@ -76,21 +75,17 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
}
@override String getTitle() {
return Strings.of(context).carryingPurchase();
return StringsLocalization.carryingPurchase();
}
@override getHint() {
return Strings.of(context).sum();
return StringsLocalization.sum();
}
@override getMenuButtons(BuildContext context) {
@override getMenuButtons() {
return <Widget>[getFaqButton(), getLogoutButton()];
}
@override Color getTextFilledBackground() {
return Colors.white;
}
@override getTextWidget() {
return new TextField(
keyboardType: TextInputType.number,
@@ -109,10 +104,12 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
);
}
getLoyality(String url) async {
getLoyalty(String url) async {
if (await platform.invokeMethod('isOnline')) {
String token = await platform.invokeMethod('getToken');
var headers = {
'DM-Authorization': 'dmapptoken $appToken',
'Authorization': 'dmtoken ${token}'
@@ -126,11 +123,11 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
String type = bonuses['type'];
setState(() {
if (type == 'amount') {
this.loyality = '${user['discount']}%';
this.loyalty = '${user['discount']}%';
} else {
List amountToBonus = bonuses['amount_to_bonus'];
double loyalityVal = (double.parse(amountToBonus[1]) / amountToBonus[0]) * 100;
this.loyality = '${loyalityVal.toStringAsFixed(0)}%';
this.loyalty = '${loyalityVal.toStringAsFixed(0)}%';
}
});
}).catchError((error) {
@@ -175,20 +172,20 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
return sumTotal.toStringAsFixed(2);
}
onPurchaseClick(BuildContext context) {
onPurchaseClick() {
String val = _parseSum(controller.text);
showDialog(context: context, child: new AlertDialog(
title: new Text(Strings.of(context).confirmation()),
content: new Text(getContentMessage(val)),
title: new Text(StringsLocalization.confirmation()),
content: new Text(StringsLocalization.confirmPurchase(val)),
actions: <Widget>[
new FlatButton(
child: new Text(Strings.of(context).no()),
child: new Text(StringsLocalization.no()),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text(Strings.of(context).yes()),
child: new Text(StringsLocalization.yes()),
onPressed: () {
purchase(val);
},
@@ -196,14 +193,12 @@ class PurchaseScreenState<T> extends BaseState<PurchaseScreen> {
]));
}
getContentMessage(String val) {
return Strings.of(context).confirmPurchase();
}
purchase(String sumTotal) async {
if (await platform.invokeMethod('isOnline')) {
if (!purchaseInProgress) {
purchaseInProgress = true;
String token = await platform.invokeMethod('getToken');
platform.invokeMethod('getDocID').then((result) {
String url = user['purchases_url'];

View File

@@ -22,12 +22,12 @@ class PurchaseSuccessScreenState<T> extends BaseState<PurchaseSuccessScreen> {
String sum;
String username;
@override getMenuButtons(BuildContext context) {
@override getMenuButtons() {
return <Widget>[getFaqButton(), getLogoutButton()];
}
@override String getTitle() {
return Strings.of(context).carryingPurchase();
return StringsLocalization.carryingPurchase();
}
@override String getHint() {
@@ -36,10 +36,10 @@ class PurchaseSuccessScreenState<T> extends BaseState<PurchaseSuccessScreen> {
@override Widget getScreenContent() {
return new Column(children: <Widget>[
getValueWithDescription(Strings.of(context).buyer(), username),
getValueWithDescription(StringsLocalization.buyer(), username),
getSuccessMessage(),
new Expanded(child: new Center()),
buildButton(getScreenMargins(74.0), getScanButton())
wrapButton(getScreenMargins(74.0), getScanButton())
]);
}
@@ -49,8 +49,8 @@ class PurchaseSuccessScreenState<T> extends BaseState<PurchaseSuccessScreen> {
}
getScanButton() {
String title = Strings.of(context).scan();
return buildRaisedButton(context, title, () => startScanner(context));
String title = StringsLocalization.scan();
return buildRaisedButton(title, () => startScanner(context));
}
getSuccessMessage() {
@@ -61,7 +61,7 @@ class PurchaseSuccessScreenState<T> extends BaseState<PurchaseSuccessScreen> {
}
getMessageTitle() {
return Strings.of(context).purchaseCompleted(sum);
return StringsLocalization.purchaseCompleted(sum);
}
}

View File

@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'dart:convert'; // Пакет для обработки json с ответом от сервера.
import 'package:checker/common.dart';
import 'package:checker/consts.dart';
import 'package:checker/network.dart';
import 'package:checker/base_state.dart';
import 'package:checker/strings.dart';
@@ -14,36 +15,42 @@ class RegistrationScreen extends StatefulWidget {
class _RegistrationScreenState extends BaseState<RegistrationScreen> {
@override String getTitle(BuildContext ctx) {
return "registration";
@override String getTitle() {
return StringsLocalization.registration();
}
@override getHint(BuildContext ctx) {
return "idStore()";
@override getHint() {
return StringsLocalization.idStore();
}
// Список виджетов, автоматически прокручиваемый вверх при открытии клавиатуры.
@override Widget getScreenContent(BuildContext ctx) {
print(new Strings().registration());
/// Список виджетов, автоматически прокручиваемый вверх при открытии клавиатуры.
@override Widget getScreenContent() {
return new Container(
child: new ListView(children: <Widget>[
new Column(children: <Widget>[
getLogo(),
getHintLabel(ctx),
getInputField(ctx),
getButton(ctx)])
getHintLabel(),
getInputField(),
getButton()])
]));
}
@override getTextWidget() {
return new TextField(keyboardType: TextInputType.number,
decoration: new InputDecoration.collapsed(hintText: getHint(),
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
onChanged: (text) => handleUserInput(text));
}
/// Возвращает кнопку регистрации.
getButton(BuildContext ctx) {
getButton() {
return new Container(margin: new EdgeInsets.only(top: 36.0), child:
buildRaisedButton(ctx, "signUp()", getOnPressed(ctx)));
buildRaisedButton(StringsLocalization.signUp(), getOnPressed()));
}
// Возвращает обработчик нажатий на кнопку регистрации.
getOnPressed(BuildContext ctx) {
return _isValidMerchantID() && !loading ? () => _registerShop(ctx) : null;
getOnPressed() {
return _isValidMerchantID() && !loading ? () => _registerShop() : null;
}
/// Токен кассы - это DIN код. DIN код - это специальный код динекта, максимальная его длина - 25 символов.
@@ -53,15 +60,15 @@ class _RegistrationScreenState extends BaseState<RegistrationScreen> {
}
/// Показать progressBar, запросить токен.
_registerShop(BuildContext ctx) {
_registerShop() {
setState(() {
loading = true;
_register(ctx);
_register();
});
}
/// Получение от платформы id установки, формирование запроса на получение токена, сохранение токена.
_register(BuildContext ctx) async {
_register() async {
if (await platform.invokeMethod('isOnline')) {
createToken(textFieldValue, await platform.invokeMethod('getPosID')).then((response) {
@@ -69,14 +76,15 @@ class _RegistrationScreenState extends BaseState<RegistrationScreen> {
error = null;
loading = false;
});
print(response.body);
Map parsedMap = JSON.decode(response.body);
if (response.statusCode == 201) {
token = parsedMap['token'];
String token = parsedMap['token'];
platform.invokeMethod('saveToken', {'token' : token});
platform.invokeMethod('saveMerchantID', {'merchantID' : textFieldValue});
pushRoute(ctx, new FinishRegistrationScreen());
pushRoute(context, new FinishRegistrationScreen());
} else {
setState(() {
error = parsedMap['errors'][0];

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'dart:convert';
@@ -16,14 +17,14 @@ class SplashScreen extends StatelessWidget {
Widget build(BuildContext context) {
// Появляется splash screen, проверяется токен.
Strings s = new Strings();
s.load("ru").then((_) {
showNextScreen(context);
new Future.delayed(const Duration(milliseconds: 500), () {
platform.invokeMethod("getLocale").then((locale) {
Intl.defaultLocale = locale;
print(Intl.defaultLocale);
showNextScreen(context);
});
});
// new Future.delayed(const Duration(milliseconds: 500), () {
// });
return new Stack(children: <Widget>[getSplashBackground(), getLogo(),
new Align(alignment: FractionalOffset.bottomRight, child:
new Container(margin: new EdgeInsets.only(right: 11.0, bottom: 5.0), child:
@@ -48,7 +49,7 @@ class SplashScreen extends StatelessWidget {
/// Запуск следующего экрана приложения.
showNextScreen(BuildContext context) async {
token = await platform.invokeMethod('getToken');
String token = await platform.invokeMethod('getToken');
// В случае, если в приложении отсутствует токен,
// необходимо запустить регистрацию кассы.

View File

@@ -1,45 +1,42 @@
import 'package:intl/intl.dart';
import 'i18n/messages_all.dart';
import 'package:sprintf/sprintf.dart';
import 'dart:async';
class Strings {
class StringsLocalization {
static final Strings _singleton = new Strings._internal();
String _localeName;
factory Strings(){
return _singleton;
}
Strings._internal();
Future load(String locale) async {
_localeName = locale;
static Future load(String locale) async {
return initializeMessages(locale);
}
String registration() => Intl.message('registration', name: 'registration', locale: _localeName);
String idStore() => Intl.message('ID_Store', name: 'ID_Store', locale: _localeName);
String signUp() => Intl.message('sign_up', name: 'sign_up', locale: _localeName);
String specifyDinStore() => Intl.message('specify_din_store', name: 'specify_din_store', locale: _localeName);
String confirmation() => Intl.message('confirmation', name: 'confirmation', locale: _localeName);
String askChangeStore() => Intl.message('ask_change_store', name: 'ask_change_store', locale: _localeName);
String yes() => Intl.message('yes', name: 'yes', locale: _localeName);
String no() => Intl.message('no', name: 'no', locale: _localeName);
String requestSentWaitActivation() => Intl.message('request_sent_wait_activ', name: 'request_sent_wait_activ', locale: _localeName);
String refreshActivationStatus() => Intl.message('update_activ_status', name: 'update_activ_status', locale: _localeName);
String appActivated() => Intl.message('app_activ', name: 'app_activ', locale: _localeName);
String completeRegistration() => Intl.message('complite_activ', name: 'complite_activ', locale: _localeName);
String cardScanner() => Intl.message('card_scaner', name: 'card_scaner', locale: _localeName);
String userName() => Intl.message('user_name', name: 'user_name', locale: _localeName);
String card() => Intl.message('card', name: 'card', locale: _localeName);
String reward() => Intl.message('reward', name: 'reward', locale: _localeName);
String sum() => Intl.message('sum', name: 'sum', locale: _localeName);
String carryingPurchase() => Intl.message('carry_purchase', name: 'carry_purchase', locale: _localeName);
String completePurchase() => Intl.message('complite_purchase', name: 'complite_purchase', locale: _localeName);
String scan() => Intl.message('scan', name: 'scan', locale: _localeName);
String buyer() => Intl.message('buyer', name: 'buyer', locale: _localeName);
String confirmPurchase() => Intl.message('confirm_purchase', name: 'confirm_purchase', locale: _localeName);
String idNotFound() => Intl.message('ID_not_found', name: 'ID_not_found', locale: _localeName);
static String confirmPurchase(String val) {
return sprintf(Intl.message('confirm_purchase', name: 'confirm_purchase', locale: Intl.defaultLocale), [val]);
}
static String purchaseCompleted(String val) {
return sprintf(Intl.message('purchase_complite', name: 'purchase_complite', locale: Intl.defaultLocale), [val]);
}
static String registration() => Intl.message('registration', name: 'registration', locale: Intl.defaultLocale);
static String idStore() => Intl.message('ID_Store', name: 'ID_Store', locale: Intl.defaultLocale);
static String signUp() => Intl.message('sign_up', name: 'sign_up', locale: Intl.defaultLocale);
static String specifyDinStore() => Intl.message('specify_din_store', name: 'specify_din_store', locale: Intl.defaultLocale);
static String confirmation() => Intl.message('confirmation', name: 'confirmation', locale: Intl.defaultLocale);
static String askChangeStore() => Intl.message('ask_change_store', name: 'ask_change_store', locale: Intl.defaultLocale);
static String yes() => Intl.message('yes', name: 'yes', locale: Intl.defaultLocale);
static String no() => Intl.message('no', name: 'no', locale: Intl.defaultLocale);
static String requestSentWaitActivation() => Intl.message('request_sent_wait_activ', name: 'request_sent_wait_activ', locale: Intl.defaultLocale);
static String refreshActivationStatus() => Intl.message('update_activ_status', name: 'update_activ_status', locale: Intl.defaultLocale);
static String appActivated() => Intl.message('app_activ', name: 'app_activ', locale: Intl.defaultLocale);
static String completeRegistration() => Intl.message('complite_activ', name: 'complite_activ', locale: Intl.defaultLocale);
static String cardScanner() => Intl.message('card_scaner', name: 'card_scaner', locale: Intl.defaultLocale);
static String userName() => Intl.message('user_name', name: 'user_name', locale: Intl.defaultLocale);
static String card() => Intl.message('card', name: 'card', locale: Intl.defaultLocale);
static String reward() => Intl.message('reward', name: 'reward', locale: Intl.defaultLocale);
static String sum() => Intl.message('sum', name: 'sum', locale: Intl.defaultLocale);
static String carryingPurchase() => Intl.message('carry_purchase', name: 'carry_purchase', locale: Intl.defaultLocale);
static String completePurchase() => Intl.message('complite_purchase', name: 'complite_purchase', locale: Intl.defaultLocale);
static String scan() => Intl.message('scan', name: 'scan', locale: Intl.defaultLocale);
static String buyer() => Intl.message('buyer', name: 'buyer', locale: Intl.defaultLocale);
static String idNotFound() => Intl.message('ID_not_found', name: 'ID_not_found', locale: Intl.defaultLocale);
}