Files
checker/lib/screens/registration.dart
2018-03-12 21:41:41 +03:00

140 lines
4.5 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'dart:async';
import 'package:checker/base/base_screen.dart';
import 'package:checker/base/base_state.dart';
import 'package:checker/common.dart';
import 'package:checker/consts.dart';
import 'package:checker/db.dart';
import 'package:checker/network.dart';
import 'package:checker/screens/finish_registration.dart';
import 'package:checker/strings.dart';
import 'package:flutter/material.dart';
// Пакет для обработки json с ответом от сервера.
/// Экран регистрации магазина и кассы.
class RegistrationScreen extends BaseScreen {
RegistrationScreen(helper, app) : super(helper, app);
@override
State createState() => new RegistrationScreenState(helper, app);
}
class RegistrationScreenState extends BaseState<RegistrationScreen> {
RegistrationScreenState(SqliteHelper helper, String app) : super(helper, app);
FocusNode _focusNode = new FocusNode();
bool isAutomaticallyImplyLeading() => false;
@override
Widget build(BuildContext ctx) {
return new WillPopScope(onWillPop: () => onWillPop(), child: getMainWidget());
}
@override
String getTitle() {
return StringsLocalization.registration();
}
@override
getHintString() {
return StringsLocalization.idStore();
}
/// Список виджетов, автоматически прокручиваемый вверх при открытии клавиатуры.
@override
Widget getScreenContent() {
return new Container(child: new ListView(children: <Widget>[
new Column(children: <Widget>[
getLogo(),
getHintLabel(),
getInputField(),
getButton()
])
]));
}
@override
getTextWidget() {
return new EnsureVisibleWhenFocused(
focusNode: _focusNode,
child: new TextField(
focusNode: _focusNode,
keyboardType: TextInputType.number,
decoration: new InputDecoration.collapsed(
hintText: getHintString(),
hintStyle: new TextStyle(color: greyTextColor, fontSize: 16.0)),
onChanged: (text) => handleUserInput(text)));
}
/// Возвращает кнопку регистрации.
getButton() {
return new Container(
margin: new EdgeInsets.only(top: 36.0),
child: buildRaisedButton(StringsLocalization.signUp(), getOnPressed()));
}
// Возвращает обработчик нажатий на кнопку регистрации.
getOnPressed() {
return _isValidMerchantID() && !loading ? () => _registerShop() : null;
}
/// Токен кассы - это DIN код. DIN код - это специальный код динекта, максимальная его длина - 25 символов.
_isValidMerchantID() {
print("${merchantID.length}");
return merchantID.length > 0 && merchantID.length < 25;
}
/// Показать progressBar, запросить токен.
_registerShop() {
setState(() {
loading = true;
register();
});
}
/// Получение от платформы id установки, формирование запроса на получение токена, сохранение токена.
register() async {
if (await platform.invokeMethod('isOnline')) {
String posID = await helper.getPosID();
getCreateTokenRequest({'merchant_shop': merchantID, 'pos': posID})
.then((response) {
setState(() {
error = null;
loading = false;
});
print(response.body);
print(response.statusCode.toString());
Map parsedMap = JSON.decode(response.body);
if (response.statusCode == 201) {
helper.createSession(merchantID, posID, parsedMap['token']).then((_) {
new Future.delayed(const Duration(milliseconds: 200), () {
print('start finish registration!');
var route = new MaterialPageRoute<String>(builder: (BuildContext context) => new FinishRegistrationScreen(helper, app), fullscreenDialog: true);
Navigator.of(context).push(route).then((token) {
Navigator.of(context).pop(token);
});
});
});
} else {
setState(() {
error = parsedMap['errors'][0];
});
}
}).catchError((error) {
print(error.toString());
});
}
}
onWillPop() {
if (Theme.of(context).platform != TargetPlatform.iOS) {
platform.invokeMethod('finish');
}
}
}