Вынес дублирующийся код в базовый класс

This commit is contained in:
kifio
2017-07-23 20:35:18 +04:00
parent 8cf5d4b028
commit 3f7dc05d9e
8 changed files with 595 additions and 186 deletions

View File

@@ -1,65 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'main.dart';
import 'dart:convert'; // Пакет для обработки json с ответом от сервера.
/// TODO: Вот это все ерунда конечно, это должно обрабатыватсья через state экрана регистрации.
import 'base_state.dart';
class FinishRegistrationScreen extends StatefulWidget {
@override State createState() => new _RegistrationScreenState();
}
class _RegistrationScreenState extends State<FinishRegistrationScreen> {
bool _tokenActive = false;
String _merchantID = null;
class _RegistrationScreenState extends BaseState<FinishRegistrationScreen> {
@override Widget build(BuildContext context) {
return new Scaffold(appBar: _getAppBar(), body: _getScreen(context));
}
AppBar _getAppBar() {
return new AppBar(title: new Text("Регистрация", style: new TextStyle(fontSize: 18.0)),
backgroundColor: primaryColor, actions: <Widget>[
new IconButton(
icon: new Icon(Icons.help_outline),
onPressed: () {}
)]);
@override String getTitle() {
return "Регистрация";
}
@override getHint() {
return 'ID merchant';
}
@overide getMenuButtons() {
return <Widget>[new IconButton(icon: new Icon(Icons.help_outline), onPressed: () {})];
}
Widget _getScreen(BuildContext context) {
if (_merchantID == null) {
_getSavedMerchantID();
if (textFieldValue == "") {
_getSavedValue();
}
return new Column(children: <Widget>[
_getLogo(),
_getMerchantIDTitle(),
_getDecoratedText(),
getLogo(),
getHintLabel(),
getDecoratedTextWidget(),
_getMessage(),
_getButton(context)
]);
}
_getLogo() {
double containerHeight = 92.0;
double imageWidth = 156.0;
return new Container(height: containerHeight, child: new Image.asset(logo_png, width: imageWidth));
}
_getMerchantIDTitle() {
return new Container(margin: new EdgeInsets.only(top: 8.0, bottom: 8.0, left: 28.0, right: 28.0),
child: new Row(crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[new Text('ID Магазина', textAlign: TextAlign.left, style: new TextStyle(fontWeight: FontWeight.w300, color: greyTextColor, fontSize: 14.0))]));
}
_getDecoratedText() {
return new Container(margin: new EdgeInsets.only(left: 28.0, right: 28.0),
padding: new EdgeInsets.only(top: 12.0, bottom: 12.0, left: 16.0, right: 16.0),
decoration: _getDecoraionForMerchantId(),
child: new Row(children: <Widget>[_getMerchantIDText()]));
}
_getMerchantIDText() {
_getMerchantID() {
return new Text(_merchantID != null ? _merchantID : '', style: new TextStyle(color: Colors.black, fontSize: 16.0));
}
@@ -73,25 +54,23 @@ class _RegistrationScreenState extends State<FinishRegistrationScreen> {
});
}
Container _getMessage() {
_getMessage() {
return new Container(height: _tokenActive ? 72.0 : 108.0, decoration: _getDecoraionForMessageField(),
margin: new EdgeInsets.only(top: 20.0, left: 12.0, right: 12.0),
padding: new EdgeInsets.only(bottom: 16.0, left: 14.0, right: 14.0),
child: new Center(child: new Text(_tokenActive ? 'Программа активирована' : 'Запрос на активацию программы отправлен, дождитесь подтверждения активации администратором',
margin: new EdgeInsets.only(top: 20.0, left: 12.0, right: 12.0),
padding: new EdgeInsets.only(bottom: 16.0, left: 14.0, right: 14.0),
child: new Center(child: new Text(_getMessageText(),
textAlign: TextAlign.center, style: new TextStyle(height: 1.5, fontWeight: FontWeight.bold, fontSize: 14.0, color: _tokenActive ? tokenActiveTextColor : tokenActivateTextColor))));
}
_getMessageText() {
return _tokenActive ? 'Программа активирована' : 'Запрос на активацию программы отправлен, дождитесь подтверждения активации администратором';
}
Decoration _getDecoraionForMessageField() {
return new BoxDecoration(image: new DecorationImage(
image: new ExactAssetImage(_tokenActive ? active_token_bg_png : activate_token_bg_png), fit: _tokenActive ? BoxFit.fitWidth : BoxFit.fill));
}
Decoration _getDecoraionForMerchantId() {
return new BoxDecoration(color: textFieldBackground,
border: new Border.all(color: const Color(0xffcfd8dc), width: 1.0),
borderRadius: new BorderRadius.all(new Radius.circular(4.0)));
}
/// Метод возвращает кнопку, которая запускает отправку токена кассы на сервер.
_getButton(BuildContext context) {
double buttonHeight = 42.0;

87
lib/base_state.dart Normal file
View File

@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'dart:async';
import 'main.dart';
abstract class BaseState<T> extends State<T> {
bool loading = false;
String error = null;
String textFieldValue = "";
AppBar getAppBar() {
return new AppBar(title: new Text(getTitle(), style: new TextStyle(fontSize: 18.0)),
backgroundColor: primaryColor, actions: getMenuButtons());
}
String getTitle();
String getHint();
getMenuButtons();
/// Метод возвращает контейнер с отступами, который содержит картинку с логотипом.
getLogo() {
double containerHeight = 92.0;
double imageWidth = 156.0;
return new Container(height: containerHeight, child: new Image.asset(logo_png, width: imageWidth));
}
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(getHintText(), overflow: TextOverflow.ellipsis, textAlign: TextAlign.left,
style: new TextStyle(fontWeight: FontWeight.w300, color: error == null ? greyTextColor : primaryColor, fontSize: 14.0))]));
}
getHintText() {
if (textFieldValue.length == 0 && error == null) {
return ' ';
} else if (error != null) {
return error;
} else {
return getHint();
}
}
/// Метод возвращает контейнер с установленными отступами, в котором размещен TextField обернутый в BoxDecoration.
getDecoratedTextWidget() {
return new Container(margin: new EdgeInsets.only(left: verticalMargin, right: verticalMargin),
padding: getPaddingForTextWidget(),
decoration: getDecoraionForTextWidget(),
child: getTextWidget());
}
getPaddingForTextWidget() {
const double verticalPadding = 12.0;
const double horizontalPadding = 16.0;
return new EdgeInsets.only(top: verticalPadding,
bottom: verticalPadding,
left: horizontalPadding,
right: horizontalPadding);
}
/// Метод возвращает BoxDecoration для _getDecoratedInputField
getDecoraionForTextWidget() {
return new BoxDecoration(color: textFieldBackground,
border: new Border.all(color: textBorderColor, width: 1.0,),
borderRadius: new BorderRadius.all(new Radius.circular(4.0)));
}
Widget 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));
}
/// Индикация ...
Widget getProgressIndicator() {
return new Center(child: loading ? new CircularProgressIndicator() : null);
}
}

View File

@@ -32,12 +32,14 @@ const Color textFieldBackground = const Color(0xffefefef);
const Color tokenActiveTextColor = const Color(0xff1f5a1f);
const Color tokenActivateTextColor = const Color(0xff4e3a19);
// Margins
const double verticalMargin = 28.0;
// HttpClient
final httpClient = createHttpClient();
/// Токен кассы. Инициализируется при регистрации.
String token;
String merchantID = "";
/// Точка входа в приложение.
void main() {

View File

@@ -1,101 +1,88 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'main.dart';
import 'dart:convert';
import 'dart:async';
import 'main.dart';
import 'activate_token.dart';
import 'base_state.dart';
/// Экран проведения покупки.
class PurchaseScreen extends StatefulWidget {
@override State createState() => new _PurchaseScreenState();
}
class _PurchaseScreenState extends State<PurchaseScreen> {
bool _loading = false;
class _PurchaseScreenState extends BaseState<PurchaseScreen> {
@override Widget build(BuildContext context) {
return new Scaffold(appBar: _getAppBar(), body: _getScreen(context));
return new Scaffold(appBar: getAppBar(), body: _getScreen(context));
}
AppBar _getAppBar() {
return new AppBar(title: new Text("Проведение покупки"),
actions: <Widget>[new IconButton(icon: new Icon(Icons.help_outline), onPressed: () {})]);
@override String getTitle() {
return "Проведение покупки";
}
@override getHint() {
return 'Сумма';
}
@overide getMenuButtons() {
return <Widget>[new IconButton(icon: new Icon(Icons.help_outline), onPressed: () {})];
}
Widget _getScreen(BuildContext context) {
return new Stack(children: <Widget>[_getScreenContent(), _getProgressIndicator()]);
return new Stack(children: <Widget>[_getScreenContent(context), getProgressIndicator()]);
}
Widget _getScreenContent() {
return new Container(height: 332.0,
Widget _getScreenContent(BuildContext context) {
return new Container(height: 398.0,
child: new ListView(reverse: true, children: <Widget>[
new Column(children: <Widget>[
_getValueWithTitle('ФИО', 'Знаменитый Рокер Паук'),
_getValueWithTitle('Карта', 'B0399900702'),
_getValueWithTitle('Вознаграждение', '100%'),
_getButton(context),
_getButton(context)])
getHintLabel(),
getDecoratedTextWidget(),
_getApprovePurchaseButton(context),
_getScanButton(context)])
].reversed.toList()));
}
Widget _getProgressIndicator() {
return new Center(child: _loading ? new CircularProgressIndicator() : null);
}
Widget _getValueWithTitle(String title, String value) {
return new Column(children: <Widget>[
return new Container(padding: new EdgeInsets.only(left: verticalMargin, right: verticalMargin, top: 12.0),
child: new Column(children: <Widget>[
new Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[new Text(title, textAlign: TextAlign.left, style: new TextStyle(color: greyTextColor, fontSize: 14.0))]),
new Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[new Text(value, textAlign: TextAlign.left, style: new TextStyle(color: Colors.black, fontSize: 20.0))])
]);
]));
}
Widget _getButton(BuildContext context) {
return new Container(margin: new EdgeInsets.only(top: 36.0), height: 42.0,
padding: new EdgeInsets.only(left: 40.0, right: 40.0),
child: new RaisedButton(child: new Text('ЗАРЕГИСТРИРОВАТЬ',
Widget _getApprovePurchaseButton(BuildContext context) {
return new Container(margin: new EdgeInsets.only(top: 36.0), height: 42.0,
child: new RaisedButton(child: new Text('ЗАФИКСИРОВАТЬ ПОКУПКУ',
style: new TextStyle(color: Colors.white)),
onPressed: null,
onPressed: () => _purchase(),
color: primaryColor));
}
Widget _getCircularProgressIndicator() {
return new Center(child: new CircularProgressIndicator());
Widget _getScanButton(BuildContext context) {
return new Container(margin: new EdgeInsets.only(top: 36.0), height: 42.0,
child: new RaisedButton(child: new Container(height: 42.0, child: new Text('СКАНИРОВАТЬ',
style: new TextStyle(color: Colors.white)),
decoration: getDecoraionForScanButton()),
onPressed: () => _purchase()));
}
getDecoraionForScanButton() {
return new BoxDecoration(
border: new Border.all(color: primaryColor, width: 1.0),
borderRadius: new BorderRadius.all(new Radius.circular(4.0)));
}
_purchase() {
print('purchase');
}
_register(BuildContext context) async {
// const platform = const MethodChannel('com.dinect.checker/instance_id');
// String url = intUrl + 'tokens/?_dmapptoken=' + intToken;
// String pos = await platform.invokeMethod('getInstanceID');
// print(pos);
// String userAgent = 'dm-checker-test v1.0.1';
// var body = {
// 'merchant_shop': merchantShop,
// 'pos': pos,
// 'description': userAgent + '-' + pos
// };
// print(url);
// for (var value in body.values) {
// print(value);
// }
// httpClient.post(url, body: body).then((response) {
// print(response.body);
// Map parsedMap = JSON.decode(response.body);
// token = parsedMap['token'];
// platform.invokeMethod('saveToken', {'token' : token}).then((value) {
// print(value.toString());
// });
// setState(() {
// loading = false;
// });
// pushRoute(context, new FinishRegistrationScreen());
// }).catchError((error) {
// print(error.toString());
// });
}
}

View File

@@ -1,9 +1,11 @@
import 'dart:convert'; // Пакет для обработки json с ответом от сервера.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'main.dart';
import 'dart:convert'; // Пакет для обработки json с ответом от сервера.
import 'dart:async';
import 'main.dart';
import 'activate_token.dart';
import 'base_state.dart';
/// На фото мой сын, большой любитель голых констант.
@@ -12,22 +14,26 @@ class RegistrationScreen extends StatefulWidget {
@override State createState() => new _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
String error = null;
bool _loading = false;
class _RegistrationScreenState extends BaseState<RegistrationScreen> {
@override build(BuildContext context) {
return new Scaffold(appBar: _getAppBar(), body: _getScreen(context));
return new Scaffold(appBar: getAppBar(), body: _getScreen(context));
}
_getAppBar() {
return new AppBar(title: new Text("Регистрация"),
actions: <Widget>[new IconButton(icon: new Icon(Icons.help_outline), onPressed: () {})]);
@override String getTitle() {
return "Регистрация";
}
@override getHint() {
return 'ID merchant';
}
@overide getMenuButtons() {
return <Widget>[new IconButton(icon: new Icon(Icons.help_outline), onPressed: () {})];
}
_getScreen(BuildContext context) {
return new Stack(children: <Widget>[_getScreenContent(), _getProgressIndicator()]);
return new Stack(children: <Widget>[_getScreenContent(), getProgressIndicator()]);
}
/// Высота контейнера задана для того, чтобы элементы располагались вверху экрана
@@ -36,69 +42,13 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
return new Container(height: 332.0,
child: new ListView(reverse: true, children: <Widget>[
new Center(child: new Column(children: <Widget>[
_getLogo(),
_getMerchantIDTitle(),
_getDecoratedInputField(),
getLogo(),
getHintLabel(),
getDecoratedTextWidget(),
_getButton(context)]))
].reversed.toList()));
}
/// Индикация отправки токена кассы.
_getProgressIndicator() {
return new Center(child: _loading ? new CircularProgressIndicator() : null);
}
/// Метод возвращает контейнер с отступами, который содержит картинку с логотипом.
/// Картинка должна
_getLogo() {
double containerHeight = 162.0;
double imageHeight = 24.0;
double imageWidth = 156.0;
return new Container(height: containerHeight, child: new Image.asset(logo_png, height: imageHeight, width: imageWidth));
}
_getMerchantIDTitle() {
return new Container(margin: new EdgeInsets.only(top: 8.0, bottom: 8.0, left: 28.0, right: 28.0),
child: new Row(crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[new Container(padding: new EdgeInsets.only(right: 8.0), child: new Text(_getMerchantIDTitleText(), overflow: TextOverflow.ellipsis, textAlign: TextAlign.left,
style: new TextStyle(fontWeight: FontWeight.w300, color: error == null ? greyTextColor : primaryColor, fontSize: 14.0)))]));
}
_getMerchantIDTitleText() {
if (merchantID.length == 0 && error == null) {
return ' ';
} else if (error != null) {
return error;
} else {
return 'ID Магазина';
}
}
/// Метод возвращает контейнер с установленными отступами, в котором размещен TextField обернутый в BoxDecoration.
_getDecoratedInputField() {
double margin = 28.0;
double verticalPadding = 12.0;
double horizontalPadding = 16.0;
return new Container(margin: new EdgeInsets.only(left: margin, right: margin),
padding: new EdgeInsets.only(top: verticalPadding, bottom: verticalPadding, left: horizontalPadding, right: horizontalPadding),
decoration: _getDecoraionForInputField(),
child: _getInputField());
}
/// Метод возвращает TextField для _getDecoratedInputField
_getInputField() {
return new TextField(keyboardType: TextInputType.number, decoration: new InputDecoration.collapsed(hintText: merchantIDHint,
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
onChanged: (text) => _handleUserInput(text));
}
/// Метод возвращает BoxDecoration для _getDecoratedInputField
_getDecoraionForInputField() {
return new BoxDecoration(color: textFieldBackground,
border: new Border.all(color: textBorderColor, width: 1.0,),
borderRadius: new BorderRadius.all(new Radius.circular(4.0)));
}
/// Метод возвращает кнопку, которая запускает отправку токена кассы на сервер.
_getButton(BuildContext context) {
double buttonHeight = 42.0;
@@ -108,26 +58,26 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
padding: new EdgeInsets.only(left: horizontalPadding, right: horizontalPadding),
child: new RaisedButton(child: new Text('ЗАРЕГИСТРИРОВАТЬ',
style: new TextStyle(color: Colors.white)),
onPressed: _isValidMerchantID() && !_loading ? () => _registerShop(context) : null,
onPressed: _isValidMerchantID() && !loading ? () => _registerShop(context) : null,
color: primaryColor));
}
/// Токен кассы - это DIN код. DIN код - это специальный код динекта, максимальная его длина - 25 символов.
_isValidMerchantID() {
return merchantID.length > 0 && merchantID.length < 25;
return textFieldValue.length > 0 && textFieldValue.length < 25;
}
/// Смена состояния экрана при изменении текста в поле ввода.
_handleUserInput(String text) {
setState(() {
merchantID = text;
textFieldValue = text;
});
}
/// Показать индикатор, запросить токен.
_registerShop(BuildContext context) {
setState(() {
_loading = true;
loading = true;
_register(context);
});
}
@@ -135,7 +85,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
/// Экран зависает на 1 сек, после этого выполняется переход на экран потверждения токена.
_registerDemo(BuildContext context) {
new Future.delayed(const Duration(milliseconds: 1000), () {
_loading = false;
loading = false;
pushRoute(context, new FinishRegistrationScreen());
});
}
@@ -149,7 +99,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
// Поле description - необязательное.
var body = {
'merchant_shop': merchantID,
'merchant_shop': textFieldValue,
'pos': pos,
};
@@ -162,7 +112,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
print(response.body);
Map parsedMap = JSON.decode(response.body);
setState(() {
_loading = false;
loading = false;
});
if (response.statusCode == 201) {
token = parsedMap['token'];

View File

@@ -2,19 +2,22 @@ import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'main.dart';
import 'registration.dart';
import 'activate_token.dart';
import 'purchase.dart';
class SplashScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Splash скрин зависает мимнимум на 1 секунду.
// После этого начинается проверка токена.
new Future.delayed(const Duration(milliseconds: 1000), () {
// pushRoute(context, new PurchaseScreen());
_showNextScreen(context);
});