В моем приложении Flutter я хочу, чтобы на кнопке с Back Pronck Дважды приложение для смартфона было выходить. Для первого нажатия он должен отображать тост -сообщение, которое нажимает еще раз, чтобы выйти из приложения, но сейчас оно напрямую выходит. Поэтому, пожалуйста, помогите мне достичь описанной функциональности.
Я дал ниже свой код для вашей ссылки: < /p>
class DashBoardScreen extends StatefulWidget {
const DashBoardScreen({super.key});
@override
State createState() => _DashBoardScreenState();
}
class _DashBoardScreenState extends State
with WidgetsBindingObserver {
final GlobalKey keyOne = GlobalKey();
int _selectedIndex = 0;
DateTime? _lastPressed;
ConnectivityResult? _connectivityResult;
final List pageList = [
const HomeScreen(),
const AllAstrologerScreen(
fromDashBoard: true
),
const LiveSessionListScreen(),
const CallScreen(),
const BlogListScreen(
fromDashBoard: true
),
];
@override
void initState() {
super.initState();
_checkInitialConnectivity();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
if (globalCurrentUserData.firebaseId != null) {
FirebaseFirestore.instance
.collection("Users")
.doc(globalCurrentUserData.firebaseId)
.update({"userState": "Offline"});
} // Set user offline when app is paused or detached
} else if (state == AppLifecycleState.resumed) {
if (globalCurrentUserData.firebaseId != null) {
FirebaseFirestore.instance
.collection("Users")
.doc(globalCurrentUserData.firebaseId)
.update({"userState": "Online"});
} // Set user online when app is resumed
}
}
Future _checkInitialConnectivity() async {
try {
await Connectivity().checkConnectivity().then((connectionResultVal) {
if(connectionResultVal != ConnectivityResult.none){
getWebSettings(context: context);
setState(() {
_connectivityResult = connectionResultVal;
});
}else{
setState(() {
_connectivityResult = connectionResultVal;
});
}
});
} catch (e) {
setState(() {
_connectivityResult =
ConnectivityResult.none; // Fallback to no connection
});
} // Update state to reflect initial connectivity
}
Future _onWillPop() async {
debugPrint("Inside on will pop method");
// Get the inner navigator state
final navigator = keyOne.currentState;
print("current navigator state - $navigator");
if (navigator != null && navigator.canPop()) {
debugPrint("----- Popping screen inside inner Navigator ------");
navigator.pop(); // Pop a screen from the inner Navigator
return Future.value(false); // Prevent app exit
} else {
debugPrint("---- No screens to pop, handling exit ----");
final now = DateTime.now();
const exitThreshold = Duration(seconds: 2);
if (_lastPressed == null || now.difference(_lastPressed!) > exitThreshold) {
_lastPressed = now;
Fluttertoast.showToast(
msg: AppLocalizations.of(context)!.pressPhoneBackBtnMsg,
toastLength: Toast.LENGTH_SHORT,
);
return Future.value(false); // Prevent exit
}
return Future.value(true); // Allow exit
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: StreamBuilder(
initialData: _connectivityResult,
stream: Connectivity().onConnectivityChanged,
builder: (context, snapshot) {
return (_connectivityResult == ConnectivityResult.none ||
snapshot.data == ConnectivityResult.none)
? CheckInternetConnectionWidget(
snapshot: snapshot,
child: PickupLayout(
scaffold: _buildDashBoardScaffoldWidget(),
uid: globalCurrentUserData.firebaseId!,
failedScaffold: _buildDashBoardScaffoldWidget()
),
)
: PickupLayout(
scaffold: _buildDashBoardScaffoldWidget(),
uid: globalCurrentUserData.firebaseId!,
failedScaffold: _buildDashBoardScaffoldWidget()
);
}),
);
}
Widget _buildDashBoardScaffoldWidget() {
return Scaffold(
backgroundColor: semiWhiteColor,
body: Navigator(
key: keyOne,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) => pageList[_selectedIndex],
);
},
),
bottomNavigationBar: Container(
height: 70.h,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30), topRight: Radius.circular(30)).r,
boxShadow: const [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, 0.1),
spreadRadius: 0,
blurRadius: 10,
offset: Offset(0, 0), // changes position of shadow
),
],
),
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
).r,
child: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: SvgPicture.asset(
homeIcon,
colorFilter: (_selectedIndex == 0)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(blackGreyColor, BlendMode.srcIn),
),
label: AppLocalizations.of(context)!.homeText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: SvgPicture.asset(
chatIcon,
colorFilter: (_selectedIndex == 1)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.chatText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: Icon(Icons.live_tv,size: 22,color:_selectedIndex == 2 ? secondaryColor:blackGreyColor),
label: AppLocalizations.of(context)!.liveText,
backgroundColor: whiteColor
),
BottomNavigationBarItem(
icon: SvgPicture.asset(
callIcon,
colorFilter: (_selectedIndex == 3)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.callText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: SvgPicture.asset(
resourcesIcon,
colorFilter: (_selectedIndex == 4)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.resourcesText,
backgroundColor: whiteColor),
],
showSelectedLabels: true,
showUnselectedLabels: true,
currentIndex: _selectedIndex,
backgroundColor: whiteColor,
unselectedItemColor: blackGreyColor,
selectedFontSize: 12.sp,
unselectedFontSize: 12.sp,
iconSize: 22.sp,
unselectedLabelStyle: GoogleFonts.poppins(
fontWeight: FontWeight.w500,
),
selectedLabelStyle: GoogleFonts.poppins(
fontWeight: FontWeight.w500,
),
type: BottomNavigationBarType.fixed,
selectedItemColor: secondaryColor,
onTap: (index) {
if (_selectedIndex == index) return; // Prevent reloading the same tab
if (index == 2) { //If LiveSessionListScreen is selected, stack it
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LiveSessionListScreen(),
fullscreenDialog: true, // Makes it behave like a modal
),
);
} else {
// Normal behavior for other tabs
keyOne.currentState?.popUntil((route) => route.isFirst);
setState(() {
_selectedIndex = index;
});
}
},
),
),
),
);
}
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... not-workin
В моем приложении Flutter на нажатии кнопки с смартфоном обратно WillPopscope не работает ⇐ IOS
Программируем под IOS
1741694217
Anonymous
В моем приложении Flutter я хочу, чтобы на кнопке с Back Pronck Дважды приложение для смартфона было выходить. Для первого нажатия он должен отображать тост -сообщение, которое нажимает еще раз, чтобы выйти из приложения, но сейчас оно напрямую выходит. Поэтому, пожалуйста, помогите мне достичь описанной функциональности.
Я дал ниже свой код для вашей ссылки: < /p>
class DashBoardScreen extends StatefulWidget {
const DashBoardScreen({super.key});
@override
State createState() => _DashBoardScreenState();
}
class _DashBoardScreenState extends State
with WidgetsBindingObserver {
final GlobalKey keyOne = GlobalKey();
int _selectedIndex = 0;
DateTime? _lastPressed;
ConnectivityResult? _connectivityResult;
final List pageList = [
const HomeScreen(),
const AllAstrologerScreen(
fromDashBoard: true
),
const LiveSessionListScreen(),
const CallScreen(),
const BlogListScreen(
fromDashBoard: true
),
];
@override
void initState() {
super.initState();
_checkInitialConnectivity();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
if (globalCurrentUserData.firebaseId != null) {
FirebaseFirestore.instance
.collection("Users")
.doc(globalCurrentUserData.firebaseId)
.update({"userState": "Offline"});
} // Set user offline when app is paused or detached
} else if (state == AppLifecycleState.resumed) {
if (globalCurrentUserData.firebaseId != null) {
FirebaseFirestore.instance
.collection("Users")
.doc(globalCurrentUserData.firebaseId)
.update({"userState": "Online"});
} // Set user online when app is resumed
}
}
Future _checkInitialConnectivity() async {
try {
await Connectivity().checkConnectivity().then((connectionResultVal) {
if(connectionResultVal != ConnectivityResult.none){
getWebSettings(context: context);
setState(() {
_connectivityResult = connectionResultVal;
});
}else{
setState(() {
_connectivityResult = connectionResultVal;
});
}
});
} catch (e) {
setState(() {
_connectivityResult =
ConnectivityResult.none; // Fallback to no connection
});
} // Update state to reflect initial connectivity
}
Future _onWillPop() async {
debugPrint("Inside on will pop method");
// Get the inner navigator state
final navigator = keyOne.currentState;
print("current navigator state - $navigator");
if (navigator != null && navigator.canPop()) {
debugPrint("----- Popping screen inside inner Navigator ------");
navigator.pop(); // Pop a screen from the inner Navigator
return Future.value(false); // Prevent app exit
} else {
debugPrint("---- No screens to pop, handling exit ----");
final now = DateTime.now();
const exitThreshold = Duration(seconds: 2);
if (_lastPressed == null || now.difference(_lastPressed!) > exitThreshold) {
_lastPressed = now;
Fluttertoast.showToast(
msg: AppLocalizations.of(context)!.pressPhoneBackBtnMsg,
toastLength: Toast.LENGTH_SHORT,
);
return Future.value(false); // Prevent exit
}
return Future.value(true); // Allow exit
}
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: StreamBuilder(
initialData: _connectivityResult,
stream: Connectivity().onConnectivityChanged,
builder: (context, snapshot) {
return (_connectivityResult == ConnectivityResult.none ||
snapshot.data == ConnectivityResult.none)
? CheckInternetConnectionWidget(
snapshot: snapshot,
child: PickupLayout(
scaffold: _buildDashBoardScaffoldWidget(),
uid: globalCurrentUserData.firebaseId!,
failedScaffold: _buildDashBoardScaffoldWidget()
),
)
: PickupLayout(
scaffold: _buildDashBoardScaffoldWidget(),
uid: globalCurrentUserData.firebaseId!,
failedScaffold: _buildDashBoardScaffoldWidget()
);
}),
);
}
Widget _buildDashBoardScaffoldWidget() {
return Scaffold(
backgroundColor: semiWhiteColor,
body: Navigator(
key: keyOne,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
builder: (context) => pageList[_selectedIndex],
);
},
),
bottomNavigationBar: Container(
height: 70.h,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30), topRight: Radius.circular(30)).r,
boxShadow: const [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, 0.1),
spreadRadius: 0,
blurRadius: 10,
offset: Offset(0, 0), // changes position of shadow
),
],
),
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
).r,
child: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: SvgPicture.asset(
homeIcon,
colorFilter: (_selectedIndex == 0)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(blackGreyColor, BlendMode.srcIn),
),
label: AppLocalizations.of(context)!.homeText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: SvgPicture.asset(
chatIcon,
colorFilter: (_selectedIndex == 1)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.chatText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: Icon(Icons.live_tv,size: 22,color:_selectedIndex == 2 ? secondaryColor:blackGreyColor),
label: AppLocalizations.of(context)!.liveText,
backgroundColor: whiteColor
),
BottomNavigationBarItem(
icon: SvgPicture.asset(
callIcon,
colorFilter: (_selectedIndex == 3)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.callText,
backgroundColor: whiteColor),
BottomNavigationBarItem(
icon: SvgPicture.asset(
resourcesIcon,
colorFilter: (_selectedIndex == 4)
? ColorFilter.mode(secondaryColor, BlendMode.srcIn)
: ColorFilter.mode(
blackGreyColor,
BlendMode.srcIn,
),
),
label: AppLocalizations.of(context)!.resourcesText,
backgroundColor: whiteColor),
],
showSelectedLabels: true,
showUnselectedLabels: true,
currentIndex: _selectedIndex,
backgroundColor: whiteColor,
unselectedItemColor: blackGreyColor,
selectedFontSize: 12.sp,
unselectedFontSize: 12.sp,
iconSize: 22.sp,
unselectedLabelStyle: GoogleFonts.poppins(
fontWeight: FontWeight.w500,
),
selectedLabelStyle: GoogleFonts.poppins(
fontWeight: FontWeight.w500,
),
type: BottomNavigationBarType.fixed,
selectedItemColor: secondaryColor,
onTap: (index) {
if (_selectedIndex == index) return; // Prevent reloading the same tab
if (index == 2) { //If LiveSessionListScreen is selected, stack it
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LiveSessionListScreen(),
fullscreenDialog: true, // Makes it behave like a modal
),
);
} else {
// Normal behavior for other tabs
keyOne.currentState?.popUntil((route) => route.isFirst);
setState(() {
_selectedIndex = index;
});
}
},
),
),
),
);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79500569/in-my-flutter-app-on-click-of-smart-phone-back-button-willpopscope-is-not-workin[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия