dart - On Back Press 按钮回调功能在 Flutter 中不起作用
问题描述
大家好,我一直在尝试在 Flutter 中实现 Willpopscope,但这个回调函数仍然不起作用,它仍然关闭或返回上一个屏幕,我想在用户按下后退按钮时显示警报对话框,但是而不是显示对话框,而是返回到上一个屏幕。请帮助我在哪里做错了。
编辑代码
import 'package:deep6/audio_player/click_player.dart';
import 'package:deep6/main_menu.dart';
import 'package:deep6/utility/countDown.dart';
import 'package:deep6/utility/preference.dart';
import 'package:flutter/material.dart';
import
'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SceneStory extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: Scene(
character: null,
text: null,
mainTextColor: null,
avatar: null,
lbText: null,
lbTextTarget: null,
lbTextColor: null,
rbText: null,
rbTextTarget: null,
rbTextColor: null,
),
);
}
}
class Scene extends StatefulWidget {
List<String> character = new List<String>();
List<String> text = new List<String>();
List<List<int>> mainTextColor = new List<List<int>>();
List<String> avatar = new List<String>();
List<String> lbText = new List<String>();
List<int> lbTextTarget = new List<int>();
List<List<int>> lbTextColor = new List<List<int>>();
List<String> rbText = new List<String>();
List<int> rbTextTarget = new List<int>();
List<List<int>> rbTextColor = new List<List<int>>();
Scene(
{Key key,
this.character,
this.text,
this.mainTextColor,
this.avatar,
this.lbText,
this.lbTextTarget,
this.lbTextColor,
this.rbText,
this.rbTextTarget,
this.rbTextColor})
: super(key: key);
@override
SceneState createState() => new SceneState();
}
String name, text, buttonLeftText, buttonRightText;
String avatar = 'assets/images/profile_cure.png';
int sceneId, leftTarget, rightTarget;
class SceneState extends State<Scene> with TickerProviderStateMixin {
double width, height;
List<String> content = new List<String>();
CountDown customTimer;
PrefsKeys prefs;
int mainIndex = 0;
bool isEnabled = false;
List<String> character = new List<String>();
List<String> text = new List<String>();
List<List<int>> mainTextColor = new List<List<int>>();
List<String> avatar = new List<String>();
List<String> lbText = new List<String>();
List<int> lbTextTarget = new List<int>();
List<List<int>> lbTextColor = new List<List<int>>();
List<String> rbText = new List<String>();
List<int> rbTextTarget = new List<int>();
List<List<int>> rbTextColor = new List<List<int>>();
Image charImage;
Text charName, mainText, leftText, rightText;
MaterialButton leftButton, rightButton;
ClickPlayer cPlay;
AnimationController controller;
@override
void initState() {
super.initState();
character = widget.character;
text = widget.text;
mainTextColor = widget.mainTextColor;
avatar = widget.avatar;
lbText = widget.lbText;
lbTextTarget = widget.lbTextTarget;
lbTextColor = widget.lbTextColor;
rbText = widget.rbText;
rbTextTarget = widget.rbTextTarget;
rbTextColor = widget.rbTextColor;
animation();
cPlay = new ClickPlayer();
preference();
}
void preference() async {
SharedPreferences pref = await SharedPreferences.getInstance().then((pref)
{
pref.setBool(PrefsKeys.bool_continuation, true);
});
}
void animation() async {
controller = new AnimationController(
duration: const Duration(milliseconds: 4000), vsync: this);
await controller.forward();
controller.dispose();
}
Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MenuScreen(),
),
);
print("Notifications is Clicked $payload");
}
void showNotification() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
var initializationSettingsAndroid;
var initializationSettingsIOS;
var initializationSettings;
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
initializationSettingsAndroid =
new AndroidInitializationSettings('ic_launcher');
initializationSettingsIOS = new IOSInitializationSettings();
initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
selectNotification: onSelectNotification);
var scheduledNotificationDateTime =
new DateTime.now().add(new Duration(minutes: 2));
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
'0', 'Anas', 'Notification',
importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
0,
'DEEP 6',
'NOW YOU CAN CONTINUE.',
scheduledNotificationDateTime,
platformChannelSpecifics);
print("Inside Notifications class");
}
void leftButtonClick() async {
cPlay.playClick();
mainIndex = lbTextTarget[mainIndex];
print("$mainIndex mainindex");
if (mainIndex == 18) {
showNotification();
SharedPreferences pref =
await SharedPreferences.getInstance().then((pref) {
pref.setInt(
PrefsKeys.str_timestamp, new
DateTime.now().millisecondsSinceEpoch);
pref.setString(PrefsKeys.str_character, character[mainIndex]);
pref.setString(PrefsKeys.str_mainText, text[mainIndex]);
pref.setString(PrefsKeys.str_avatar, avatar[mainIndex]);
pref.setString(PrefsKeys.str_lbText, lbText[mainIndex]);
List<String> color = new List<String>();
color.add(mainTextColor[mainIndex][0].toString());
color.add(mainTextColor[mainIndex][1].toString());
color.add(mainTextColor[mainIndex][2].toString());
pref.setStringList(PrefsKeys.list_color, color);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainMenu(),
),
);
});
} else {
isEnabled = false;
setState(() {
charImage = null;
charName = null;
mainText = null;
leftText = null;
rightText = null;
charImage = new Image.asset(
avatar[mainIndex],
fit: BoxFit.contain,
height: height * 0.2,
);
charName = new Text(
character[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2],
1.0),
fontSize: 20.0,
),
);
mainText = new Text(
text[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2],
1.0),
fontSize: 22.0,
),
textAlign: TextAlign.start,
);
animation();
leftText = new Text(
lbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(lbTextColor[mainIndex][0],
lbTextColor[mainIndex][1], lbTextColor[mainIndex][2], 1.0)),
textAlign: TextAlign.center,
softWrap: true,
maxLines: 10,
);
if (rbText[mainIndex] == "") {
rightText = null;
rightButton = new MaterialButton(
key: null,
onPressed: () {},
color: Color.fromRGBO(0, 0, 0, 0.8),
height: 0.0,
minWidth: 0.0,
child: null,
);
} else {
rightText = new Text(
rbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(rbTextColor[mainIndex][0],
rbTextColor[mainIndex][1], rbTextColor[mainIndex][2], 1.0),
),
textAlign: TextAlign.center,
);
}
});
}
}
void rightButtonClick() async {
cPlay.playClick();
mainIndex = rbTextTarget[mainIndex];
print("$mainIndex mainindex");
if (mainIndex == 18) {
showNotification();
SharedPreferences pref =
await SharedPreferences.getInstance().then((pref) {
pref.setInt(
PrefsKeys.str_timestamp, new DateTime.now().millisecondsSinceEpoch);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainMenu(),
),
);
});
} else {
isEnabled = false;
setState(() {
charImage = null;
charName = null;
mainText = null;
leftText = null;
rightText = null;
charImage = new Image.asset(
avatar[mainIndex],
fit: BoxFit.contain,
height: height * 0.2,
);
charName = new Text(
character[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2], 1.0),
fontSize: 22.0,
),
);
mainText = new Text(
text[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2], 1.0),
fontSize: 20.0,
),
textAlign: TextAlign.start,
);
animation();
leftText = new Text(
lbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(lbTextColor[mainIndex][0],
lbTextColor[mainIndex][1], lbTextColor[mainIndex][2], 1.0)),
textAlign: TextAlign.center,
softWrap: true,
maxLines: 10,
);
if (rbText[mainIndex] == "") {
rightText = null;
rightButton = new MaterialButton(
key: null,
onPressed: () {},
color: Color.fromRGBO(0, 0, 0, 0.8),
height: 0.0,
minWidth: 0.0,
child: null,
);
} else {
rightText = new Text(
rbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(rbTextColor[mainIndex][0],
rbTextColor[mainIndex][1], rbTextColor[mainIndex][2], 1.0),
),
textAlign: TextAlign.center,
);
}
});
}
}
Future<bool> _showDialog() {
print("Show dialog");
return showDialog(
context: context,
builder: (BuildContext contxt) {
return AlertDialog(
title: new Text(
"Exit!!!",
style: TextStyle(color: Colors.black),
),
content: new Text(
"Are You sure you want to exit?",
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
new FlatButton(
child: new Text(
"Yes",
style: TextStyle(color: Colors.blue),
),
onPressed: null,
)
],
);
});
}
@override
Widget build(BuildContext context) {
final mediaQueryData = MediaQuery.of(context);
width = mediaQueryData.size.width;
height = mediaQueryData.size.height;
Animation<int> _characterCount = new StepTween(
begin: 0, end: text[mainIndex].length)
.animate(new CurvedAnimation(parent: controller, curve: Curves.easeIn));
controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
isEnabled = true;
}
});
charImage = new Image.asset(
avatar[mainIndex],
fit: BoxFit.contain,
height: height * 0.2,
);
charName = new Text(
character[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2], 1.0),
fontSize: 22.0,
),
);
mainText = new Text(
text[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1], mainTextColor[mainIndex][2], 1.0),
fontSize: 20.0,
),
textAlign: TextAlign.start,
);
leftText = new Text(
lbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(lbTextColor[mainIndex][0],
lbTextColor[mainIndex][1], lbTextColor[mainIndex][2], 1.0)),
textAlign: TextAlign.center,
softWrap: true,
maxLines: 10,
);
rightText = new Text(
rbText[mainIndex],
style: new TextStyle(
color: Color.fromRGBO(rbTextColor[mainIndex][0],
rbTextColor[mainIndex][1], rbTextColor[mainIndex][2], 1.0),
),
textAlign: TextAlign.center,
);
leftButton = new MaterialButton(
key: null,
onPressed: () {
if (isEnabled) {
leftButtonClick();
}
},
color: Color.fromRGBO(0, 0, 0, 0.8),
height: height * 0.2,
minWidth: width * 0.49,
child: new Container(
child: leftText,
),
);
rightButton = new MaterialButton(
key: null,
onPressed: () {
if (isEnabled) {
rightButtonClick();
}
},
color: Color.fromRGBO(0, 0, 0, 0.8),
height: height * 0.2,
minWidth: width * 0.49,
child: rightText,
);
return new WillPopScope(
child: new Scaffold(
backgroundColor: new Color(0xFF000000),
body: new Container(
height: double.infinity,
width: double.infinity,
decoration: new BoxDecoration(
image: DecorationImage(
image: new AssetImage('assets/images/blury_background.png'),
fit: BoxFit.fill)),
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
charImage,
new Container(
padding: const EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 5.0),
child: new Center(
child: charName,
),
color: Color.fromRGBO(0, 0, 0, 0.8),
),
new AnimatedBuilder(
animation: _characterCount,
builder: (BuildContext context, Widget child) {
String txt =
text[mainIndex].substring(0, _characterCount.value);
return new Container(
color: Color.fromRGBO(0, 0, 0, 0.8),
child: new Text(
txt,
style: new TextStyle(
color: Color.fromRGBO(
mainTextColor[mainIndex][0],
mainTextColor[mainIndex][1],
mainTextColor[mainIndex][2],
1.0),
fontSize: 20.0,
),
textAlign: TextAlign.start,
),
padding: const EdgeInsets.all(20.0),
//fromLTRB(12.0, 0.0, 5.0, 0.0),
height: height * 0.5,
);
}),
new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
child: leftButton,
),
new Container(
child: rightButton,
),
],
),
]),
),
),
onWillPop: () {
print("on back is pressed");
},
);
}
}
这是我全班的代码。现在请帮助我,我做错了。
解决方案
尝试只包裹body
,WillPopScope
而不是整体Scaffold
UPD
如果我理解正确 - 你这样称呼这个屏幕:
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SceneStory()));
那样做
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Scene()));
推荐阅读
- reactjs - GatsbyJs 从 onRouteUpdate 更新提供者值
- php - 更改方法 A 中的类属性值并访问方法 B 中的更新值
- r - 在 R 中按条件连接表
- python-3.x - 规范化熊猫数据框的所有列(作为一列)
- java - FirebaseRecyclerAdapter 未在我的 RecyclerView 布局中显示数据
- python - 清理数据框列以进行分类
- .net - 在 Visual Studio 2019 中将警告视为错误进行构建但不是智能感知
- sql-server - BEGIN TRY and EXECUTE 动态简单查询错误
- python - 在 python 中,是否有一种最佳实践方法来清理包含需要转义的字符的正则表达式搜索字符串?
- excel - 我如何通过从 excel 获取信息来对多个网页进行数据输入