Files
checker/lib/common.dart

111 lines
3.9 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 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'network.dart';
import 'purchase.dart';
import 'faq.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);
Navigator.of(context).pushReplacement(route);
}
// Добавление route, с возможностью вернуться к предыдущему экрану.
faq(BuildContext context) {
var route = new MaterialPageRoute<Null>(builder: (BuildContext context) => new FAQScreen());
Navigator.of(context).push(route);
}
// В методе отправляется запрос на удаление токена кассы, очищаются SharedPreferences приложения.
logout(BuildContext context) {
VoidCallback positiveCalback = () {
if (token != null) {
deleteToken(token).then((response) async {
print(response.body);
await platform.invokeMethod('removeKeys');
pushRoute(context, new RegistrationScreen()); // Запускаем регистрацию
}).catchError((error) {
print(error.toString());
});
} else {
Navigator.of(context).pop();
Navigator.of(context).pop();
}
};
showYesNoDialog(context, 'Подтверждение', 'Вы действительно хотите выйти и ввести другой номер магазина?', positiveCalback);
}
/// Запуск спецефичной для каждой платформы части приложения - сканера.
/// Может производиться с нескольких экранов (splash, finish_registration).
startScanner(BuildContext context) async {
// Канал ловит вызовы методов из "нативной" части приложения.
// Могут быть вызваны либо logaut либо faq, либо purchase.
if (token != null) {
platform.setMethodCallHandler((MethodCall call) async {
print('call.method: ${call.method}');
if (call.method == 'logout') {
logout(context);
} else if (call.method == 'faq') {
faq(context);
} else {
List usersList = JSON.decode(call.arguments);
print('usersList.length: ${usersList.length}');
if (usersList.length > 0) {
pushRoute(context, new PurchaseScreen(usersList[0], card));
}
// var card = ;
// String url = 'http://pos-api-int.dinect.com/20130701/users/?auto=${card}';
// print('url: ' + url);
// var headers = {
// 'DM-Authorization': 'dmapptoken 9fec83cdca38c357e6b65dbb17514cdd36bf2a08',
// 'Authorization': 'dmtoken ${token}'
// };
// httpClient.get(url, headers: headers).then((response) {
// print(response.body);
// }).catchError((error) {
// print(error.toString());
// });
}
});
}
await platform.invokeMethod('startScanner');
}
// Запуск диалога с двумя кнопками
showYesNoDialog(BuildContext context, String title, String content, VoidCallback positiveCallback) {
showDialog(context: context, child: new AlertDialog(
title: new Text(title),
content: new Text(content),
actions: <Widget>[
new FlatButton(
child: new Text('Нет'),
onPressed: () {
Navigator.of(context).pop();
}
),
new FlatButton(
child: new Text('Да'),
onPressed: positiveCallback)]));
}