#flutter #dart
#трепетание #dart
Вопрос:
Я хочу создать систему проверки лицензии для своего приложения, чтобы активировать ее, если лицензия введена или уже присутствует.
Если при запуске приложения лицензия не существует, я показываю страницу, которая позволяет мне сканировать ее с помощью QR-кода.
Если отсканированная лицензия действительна, я нажимаю на страницу успеха с кнопкой на ней, которая позволяет мне разблокировать приложение. Когда я нажимаю на эту кнопку, я хочу закрыть свою страницу успеха и перестроить свое приложение с разблокированной домашней страницей приложения.
Это работает до страницы успеха. Когда я нажимаю на свою кнопку, чтобы разблокировать приложение, я не могу перестроить родительскую страницу с помощью приложения unblock.
MyApp: это изменение выбирает экран, есть ли у меня лицензия или нет.
class AppScreen extends StatelessWidget {
const AppScreen({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Impact',
debugShowCheckedModeBanner: false,
theme: AppTheme().data,
home: ChangeNotifierProvider<LicenseNotifier>(
create: (BuildContext context) => LicenseNotifier(),
child: Consumer(
builder: (context, LicenseNotifier license, _) {
return license.showScreenWithLicenseState();
},
),
),
);
}
}
Уведомитель о моей лицензии:
class LicenseNotifier with ChangeNotifier {
LicenseState state = LicenseState.Uninitialized;
String getLicenseInApp;
String licenseScanned;
String personnalKey;
final String _scanBarColor = "#f57873";
LicenseNotifier(){
personnalKey = "1010";
_checkIfAppIsUnlocked();
}
Future<void> _checkIfAppIsUnlocked() async {
if (getLicenseInApp != null) {
state = LicenseState.Authenticated;
}
else{
state = LicenseState.Unauthenticated;
}
notifyListeners();
}
Future scanQRCode(BuildContext context) async{
await FlutterBarcodeScanner.scanBarcode(_scanBarColor, "Cancel", true, ScanMode.QR).then((value) {
licenseScanned = value.toString();
});
licenseValidator(context);
}
void licenseValidator(BuildContext context){
if(licenseScanned == personnalKey){
showSuccessLicenseScreen(context);
}
notifyListeners();
}
void showSuccessLicenseScreen(BuildContext context){
Navigator.push(context, MaterialPageRoute(
builder: (context) => ChangeNotifierProvider<LicenseNotifier>(
create: (BuildContext context) => LicenseNotifier(),
child: LicenseSuccessScreen(title: "Valid license")
),
));
}
activateApp(BuildContext context) {
Navigator.pop(context);
state = LicenseState.Authenticated;
notifyListeners();
}
showScreenWithLicenseState(){
switch (state) {
case LicenseState.Uninitialized:
return SplashScreen();
break;
case LicenseState.Unauthenticated:
case LicenseState.Authenticating:
return LicenseActivationScreen(title: "Activate license");
break;
case LicenseState.Authenticated:
return ChangeNotifierProvider<BottomNavigationBarNotifier>(
create: (BuildContext context) => BottomNavigationBarNotifier(),
child: NavigationBarScreen(),
);
break;
}
return null;
}
}
Экран моего успеха: когда я сканирую действительную лицензию
class LicenseSuccessScreen extends StatelessWidget{
final String title;
const LicenseSuccessScreen({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context)
{
return GestureDetector(
onTap: (() => FocusScope.of(context).requestFocus(FocusNode())),
child: Scaffold(
appBar: AppBar(
backgroundColor: AppColors.colorContrastGreen,
elevation: 0,
centerTitle: true,
title: Text(title),
),
body : _buildBody(context),
),
);
}
Widget _buildBody(BuildContext context)
{
var _licenseProvider = Provider.of<LicenseNotifier>(context);
return Container(
color: AppColors.colorContrastGreen,
padding: EdgeInsets.symmetric(horizontal: AppUi.RATIO * 5),
height: double.infinity,
child: Column(
children: [
ContainerComponent(
background: AppColors.colorBgLight,
alignement: CrossAxisAlignment.center,
children: [
ButtonComponent.primary(
context: context,
text: "Débloquer",
onPressed: () async{
_licenseProvider.activateApp(context);
},
),
],
),
],
),
);
}
}
Поэтому, когда я нажимаю на свою кнопку, которая вызывает «activateApp» в уведомителе, экран успеха закрывается, но у меня нет содержимого моего приложения. Он просто показывает экран LicenseActivationScreen. Как решить эту проблему?
Комментарии:
1. wdigetin не обнаруживает действие. Вы определили свой wigdet как StatelessWidget и измените его на StatefulWidget. Наведите указатель мыши на StatelessWidget, чтобы изменить ctrl . Вы можете перевести, нажав. Кажется, все в порядке с потоковой передачей.
2. Можно передавать данные на push-странице с помощью «.then» после «navigator.push». При этом я возвращаюсь на предыдущую страницу, нажав на кнопку со стрелкой назад, предыдущая страница обновляется. НО я хочу обновить предыдущую страницу ТОЛЬКО тогда, когда я нажимаю на плоскую кнопку на нажатой странице. Как это сделать?