flutter - Function is not invoked normally - android

I copied the video I watched on YouTube to make an Edmob banner ad.
https://www.youtube.com/watch?v=NqorHLdqyV4
Write super.initState() in the void initState() function, but it doesn't appear in my Android studio.
This is the code I wrote.
import 'dart:convert';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:app/count_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import './main.dart';
class HomePage extends StatelessWidget {
HomePage({Key? key}) : super(key: key);
final String androidTestId = 'ca-app-pub-3940256099942544/6300978111';
late CountPage _countPage; BannerAd? banner;
#override
void initState() {
super.initState();
banner = BannerAd(
listener: AdManagerBannerAdListener(),
size: AdSize.banner,
adUnitId: androidTestId,
request: AdRequest(),
)..load();
}
#override
Widget build(BuildContext context) {
_countPage = Provider.of<CountPage>(context, listen: true);
List list = jsonDecode(_countPage.arrayText);
bool toggle = false;
return Scaffold(
appBar: AppBar(
backgroundColor: _countPage.selection,
title: Text('철학 한 스푼'),
centerTitle: true, // 중앙 정렬
elevation: 0.0,
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
// currentAccountPicture: CircleAvatar(
// backgroundImage: AssetImage('캡처.png'), // 앱 아이콘 들어갈자리
// backgroundColor: Colors.white,
// ),
accountName: Text('철학 한 스푼'),
accountEmail: Text("개발자 이메일: kaingsik13#naver.com"),
decoration: BoxDecoration(
color: _countPage.selection,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40.0),
bottomRight: Radius.circular(40.0),
)),
),
ListTile(
leading: Icon(
Icons.home,
color: Colors.grey[850],
),
title: Text('메인 화면'),
onTap: () {
print('메인 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.settings,
color: Colors.grey[850],
),
title: Text('설정'),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) {
return Option_page();
}));
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('리뷰 쓰기'),
onTap: () {
print('리뷰 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('후원 하기(광고 제거)'),
onTap: () {
print('후원 화면 확인');
},
),
],
),
),
body: Container(
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.page_down();
},
icon: Icon(Icons.chevron_left),
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
alignment: Alignment(0.0, 0.0),
color: Colors.white,
child: Text(
list[_countPage.page]["message"],
style: TextStyle(
fontSize: _countPage.font,
fontFamily: 'snow',
),
textAlign: _countPage.align,
),
),
),
Container(
height: 40,
width: 300,
color: Colors.white,
child: Center(
child: Text(
list[_countPage.page]["author"],
style: TextStyle(fontSize: 20, color: Colors.black),
))),
Container(
child: AnimatedOpacity(
opacity: _countPage.visible ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
child: Container(
height: 50,
width: 70,
color: Colors.black38,
child: Center(
child: Text("복사 확인",
style: TextStyle(
fontSize: 15, color: Colors.white)))),
),
),
],
),
),
Center(
child: IconButton(
onPressed: () {
_countPage.page_up();
},
icon: Icon(Icons.chevron_right)))
],
),
),
bottomNavigationBar: BottomAppBar(
color: _countPage.selection,
child: Container(
height: 150,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.copy_on();
Clipboard.setData(ClipboardData(
text: list[_countPage.page]["message"]));
Future.delayed(Duration(milliseconds: 800), () {
_countPage.copy_on();
});
},
icon: Icon(Icons.content_copy))),
Center(
child: IconButton(
onPressed: () {
Share.share(list[_countPage.page]["message"]);
},
icon: Icon(Icons.share))),
],
),
Container(
height: 100,
color: Colors.green[50],
child: this.banner == null
? Container()
: AdWidget(
ad: this.banner!,
),
),
],
),
),
),
);
}
}
Forced super.initState();
I've tried, but an error occurs.
If there's a problem with my code or if there's any improvement in the way I ask questions, I want you to tell me without hesitation.
I can show you all the code I wrote.

You are having StatelessWidget, but initState will be available only on StatefulWidget's State
Your code should be as following
import 'dart:convert';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:app/count_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import './main.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final String androidTestId = 'ca-app-pub-3940256099942544/6300978111';
late CountPage _countPage;
BannerAd? banner;
#override
void initState() {
super.initState();
banner = BannerAd(
listener: AdManagerBannerAdListener(),
size: AdSize.banner,
adUnitId: androidTestId,
request: AdRequest(),
)..load();
}
#override
Widget build(BuildContext context) {
_countPage = Provider.of<CountPage>(context, listen: true);
List list = jsonDecode(_countPage.arrayText);
bool toggle = false;
return Scaffold(
appBar: AppBar(
backgroundColor: _countPage.selection,
title: Text('철학 한 스푼'),
centerTitle: true, // 중앙 정렬
elevation: 0.0,
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
// currentAccountPicture: CircleAvatar(
// backgroundImage: AssetImage('캡처.png'), // 앱 아이콘 들어갈자리
// backgroundColor: Colors.white,
// ),
accountName: Text('철학 한 스푼'),
accountEmail: Text("개발자 이메일: kaingsik13#naver.com"),
decoration: BoxDecoration(
color: _countPage.selection,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40.0),
bottomRight: Radius.circular(40.0),
)),
),
ListTile(
leading: Icon(
Icons.home,
color: Colors.grey[850],
),
title: Text('메인 화면'),
onTap: () {
print('메인 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.settings,
color: Colors.grey[850],
),
title: Text('설정'),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) {
return Option_page();
}));
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('리뷰 쓰기'),
onTap: () {
print('리뷰 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('후원 하기(광고 제거)'),
onTap: () {
print('후원 화면 확인');
},
),
],
),
),
body: Container(
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.page_down();
},
icon: Icon(Icons.chevron_left),
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
alignment: Alignment(0.0, 0.0),
color: Colors.white,
child: Text(
list[_countPage.page]["message"],
style: TextStyle(
fontSize: _countPage.font,
fontFamily: 'snow',
),
textAlign: _countPage.align,
),
),
),
Container(
height: 40,
width: 300,
color: Colors.white,
child: Center(
child: Text(
list[_countPage.page]["author"],
style: TextStyle(fontSize: 20, color: Colors.black),
))),
Container(
child: AnimatedOpacity(
opacity: _countPage.visible ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
child: Container(
height: 50,
width: 70,
color: Colors.black38,
child: Center(
child: Text("복사 확인",
style: TextStyle(
fontSize: 15, color: Colors.white)))),
),
),
],
),
),
Center(
child: IconButton(
onPressed: () {
_countPage.page_up();
},
icon: Icon(Icons.chevron_right)))
],
),
),
bottomNavigationBar: BottomAppBar(
color: _countPage.selection,
child: Container(
height: 150,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.copy_on();
Clipboard.setData(ClipboardData(
text: list[_countPage.page]["message"]));
Future.delayed(Duration(milliseconds: 800), () {
_countPage.copy_on();
});
},
icon: Icon(Icons.content_copy))),
Center(
child: IconButton(
onPressed: () {
Share.share(list[_countPage.page]["message"]);
},
icon: Icon(Icons.share))),
],
),
Container(
height: 100,
color: Colors.green[50],
child: this.banner == null
? Container()
: AdWidget(
ad: this.banner!,
),
),
],
),
),
),
);
}
}

Related

Flutter - How do I get the app to run right after the phone lock screen?

I'm building a motivational app.
I want the app to run as soon as people turn on their phones and unlock the lock screen.
I tried using auto_start_flutter that I learned through Googleing.
import 'dart:async';
import 'dart:convert';
// import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:app/count_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:auto_start_flutter/auto_start_flutter.dart';
import './main.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final String androidTestId = 'ca-app-pub-3940256099942544/6300978111';
late CountPage _countPage;
// BannerAd? banner;
#override
void initState() {
super.initState();
initAutoStart();
// banner = BannerAd(
// listener: AdManagerBannerAdListener(),
// size: AdSize.banner,
// adUnitId: androidTestId,
// request: AdRequest(),//..load();
}
Future<void> initAutoStart() async {
try {
//check auto-start availability.
var test = await (isAutoStartAvailable as FutureOr<bool>);
print(test);
//if available then navigate to auto-start setting page.
if (test) await getAutoStartPermission();
} on PlatformException catch (e) {
print(e);
}
if (!mounted) return;
}
#override
Widget build(BuildContext context) {
_countPage = Provider.of<CountPage>(context, listen: true);
List list = jsonDecode(_countPage.arrayText);
bool toggle = false;
return Scaffold(
appBar: AppBar(
backgroundColor: _countPage.selection,
title: Text('철학 한 스푼'),
centerTitle: true, // 중앙 정렬
elevation: 0.0,
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
// currentAccountPicture: CircleAvatar(
// backgroundImage: AssetImage('캡처.png'), // 앱 아이콘 들어갈자리
// backgroundColor: Colors.white,
// ),
accountName: Text('철학 한 스푼'),
accountEmail: Text("개발자 이메일: kaingsik13#naver.com"),
decoration: BoxDecoration(
color: _countPage.selection,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40.0),
bottomRight: Radius.circular(40.0),
)),
),
ListTile(
leading: Icon(
Icons.home,
color: Colors.grey[850],
),
title: Text('메인 화면'),
onTap: () {
print('메인 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.settings,
color: Colors.grey[850],
),
title: Text('설정'),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) {
return Option_page();
}));
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('리뷰 쓰기'),
onTap: () {
print('리뷰 화면 확인');
},
),
ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.grey[850],
),
title: Text('후원 하기(광고 제거)'),
onTap: () {
print('후원 화면 확인');
},
),
],
),
),
body: Container(
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.page_down();
},
icon: Icon(Icons.chevron_left),
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
alignment: Alignment(0.0, 0.0),
color: Colors.white,
child: Text(
list[_countPage.page]["message"],
style: TextStyle(
fontSize: _countPage.font,
fontFamily: 'snow',
),
textAlign: _countPage.align,
),
),
),
Container(
height: 40,
width: 300,
color: Colors.white,
child: Center(
child: Text(
list[_countPage.page]["author"],
style: TextStyle(fontSize: 20, color: Colors.black),
))),
Container(
child: AnimatedOpacity(
opacity: _countPage.visible ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
child: Container(
height: 50,
width: 70,
color: Colors.black38,
child: Center(
child: Text("복사 확인",
style: TextStyle(
fontSize: 15, color: Colors.white)))),
),
),
],
),
),
Center(
child: IconButton(
onPressed: () {
_countPage.page_up();
},
icon: Icon(Icons.chevron_right)))
],
),
),
bottomNavigationBar: BottomAppBar(
color: _countPage.selection,
child: Container(
height: 150,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Center(
child: IconButton(
onPressed: () {
_countPage.copy_on();
Clipboard.setData(ClipboardData(
text: list[_countPage.page]["message"]));
Future.delayed(Duration(milliseconds: 800), () {
_countPage.copy_on();
});
},
icon: Icon(Icons.content_copy))),
Center(
child: IconButton(
onPressed: () {
Share.share(list[_countPage.page]["message"]);
},
icon: Icon(Icons.share))),
],
),
Container(
height: 100,
color: Colors.green[50],
),
],
),
),
),
);
}
}
I extracted Android appk and tested it with my phone, but the app doesn't run after the lock screen.
I want my app to run as soon as I unlock the lock screen and come out.

How do i put a horizontal listview of boxdecoration under another boxdecoration?

Hellog guys im new to flutter and wanted to make a homepage with a horizontal listview below a boxdecoration for my health app.
here is my UI that i build in figma
i want to make my homepage to be like that but cant quite understand how to do it.
btw this is my current homepage so far
and this is my code
//import 'dart:js';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:medreminder/NewsArticle/news_home.dart';
import 'package:medreminder/Recipe/recipe_home.dart';
import 'package:medreminder/Reminder/ui/theme.dart';
import 'package:medreminder/TipsAndTricks/screens/tips_screen.dart';
import 'Reminder/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
import 'package:medreminder/main.dart';
import 'package:medreminder/home_page.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Mr. Health App"),
backgroundColor: Color(0XFF0080FE),
),
body: Stack(
alignment: Alignment.topCenter,
children: [
Image.asset('images/MenuImg.jpg'),
Container(
height: 250,
width: 310,
margin: const EdgeInsets.only(top: 150),
padding: const EdgeInsets.only(
left: 20,
right: 20,
top: 15,
bottom: 15,
),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(25.0)),
color: context.theme.backgroundColor,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 6),
),
],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
IconButton(
icon: Image.asset('images/reminder.png'),
iconSize: 45,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
Text("Medicine\nReminder", style: normalStyle,)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/news.png'),
iconSize: 45,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => NewsHomePage()),
);
},
),
Text(" News \n& Article", style: normalStyle)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 45,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => RecipeHomePage()),
);
},
),
Text("Healty Food \n Recipe", style: normalStyle)
],
),
],
),
SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
IconButton(
icon: Image.asset('images/tips.png'),
iconSize: 45,
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const TipsList()),
);
},
),
Text("Tips &\n Tricks", style: normalStyle,)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/about.png'),
iconSize: 45,
onPressed: () {
},
),
Text("About Us\n", style: normalStyle)
],
),
Column(
children: [
IconButton(
icon: Image.asset('images/recipe.png'),
iconSize: 45,
onPressed: () {},
),
Text("Healty Food \n Recipe", style: normalStyle)
],
),
],
)
],
),
),
],
));
}
}
i hope you guys can help me. thankyou so much
A horizontal list view can be created by ListView.builder widget. By default scroll direction of this list is vertical hence you have to change it to horizontal : -
scrollDirection: Axis.horizontal,
Full Code : -
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListView',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const View(),
);
}
}
class View extends StatefulWidget {
const View({super.key});
#override
State<View> createState() => _ViewState();
}
class _ViewState extends State<View> {
List doctorName = ["A", "B", "C"];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 236, 230, 230),
body: Padding(
padding: const EdgeInsets.only(top: 550),
child: SizedBox(
height: 240,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: doctorName.length,
itemBuilder: ((context, index) {
return (Container(
margin: EdgeInsets.only(
top: 15,
bottom: 15,
left: 25,
right: index == 2 ? 25 : 0),
padding: const EdgeInsets.only(left: 15, right: 15),
width: 360,
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
const BorderRadius.all(Radius.circular(20.0)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 5.0,
spreadRadius: 2.0,
offset: const Offset(0.0, 6.0)),
]),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const CircleAvatar(
radius: 45.0,
child: Icon(
Icons.person,
size: 45,
),
),
const SizedBox(
width: 20,
),
Column(
children: [
const SizedBox(
height: 40,
),
Text(
doctorName[index],
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700),
),
const SizedBox(
height: 10,
),
const Text(
'Text 1',
style: TextStyle(
fontSize: 18,
),
),
const Text(
'Text 2',
style: TextStyle(
fontSize: 18,
),
),
const SizedBox(
height: 10,
),
],
)
],
),
const Divider(
color: Colors.black,
thickness: 1.0,
),
const SizedBox(
height: 10,
),
const Text(
'Body ...',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w400),
),
],
),
));
})),
),
));
}
}
Output : -

Error: "I/Process ( 4121): Sending signal. PID: 4121 SIG: 9 Lost connection to device.." while using flutter on android studio

"Sending signal. PID: 4121 SIG: 9 Lost connection to device" I never seen that problem in my Android Studio IDE of my Computer. But When I was import this project on another computer and run in Emulator I saw that error .this is a ecommerce project. After the login Success the app will show Homepage. The Homepage Will show products from firebase. But the app exit.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:ecommercedemo/main.dart';
import 'package:ecommercedemo/screens/Cart.dart';
import 'package:ecommercedemo/screens/product_details_page.dart';
import 'package:ecommercedemo/screens/profile_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
class HomePage extends StatefulWidget {
//const HomePage({Key? key}) : super(key: key);
String? category;
HomePage(String category){
this.category=category;
}
#override
_HomePageState createState() => _HomePageState(category!);
}
class _HomePageState extends State<HomePage> {
String? category;
_HomePageState(String category){
this.category=category;
}
int m=0;
#override
Widget build(BuildContext context) {
final size=MediaQuery.of(context).size;
return Scaffold(
//backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.white,
title: Padding(
padding: const EdgeInsets.only(left: 0),
child: Container(
width: double.infinity,
height: 40,
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(5)),
child: Center(
child: TextField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
prefixIcon: Icon(Icons.search),
suffixIcon: IconButton(
icon: Icon(Icons.clear),
onPressed: () {
/* Clear the search field */
},
),
hintText: 'Search...',
border: InputBorder.none),
),
),
),
),
// actions: <Widget>[
// IconButton(icon: Icon(Icons.search),
// onPressed: () {
// //showSearch(context: context, delegate: DataSearch(listWords));
// })
// ],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
flex: 30,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: Color(0xffffaf38),
borderRadius: BorderRadius.circular(15)
),
alignment: Alignment.center,
height: 100,
width: size.width,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.black,
shape: CircleBorder(),
//padding: EdgeInsets.all(30)
),
onPressed: (){
mode=1;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('Kids')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/kids.png"),
radius: 30,
),
),
Text("Kids")
],
),
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder(),
//padding: EdgeInsets.all(30)
),
onPressed: (){
mode=2;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('Device')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/mensitem.png"),
radius: 30,
),
),
Text('Devices')
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=3;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('men')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/men's.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Men's")
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=4;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage("Women")), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/girls.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Women")
],
),
Column(
children: [
ElevatedButton(
onPressed: (){
mode=5;
Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context)=>HomePage('electronics')), (route) => false);
},
child: CircleAvatar(
backgroundImage: AssetImage("images/Devices.png"),
radius: 30,
),
style: ElevatedButton.styleFrom(
primary: Colors.white,
shape: CircleBorder()
),
),
Text("Electronics")
],
)
],
),
),
),
),
),
),
Expanded(
flex: 70,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: Color(0xffffaf38),
borderRadius: BorderRadius.circular(15)
),
alignment: Alignment.center,
height: size.height,
width: size.width,
child: _buildcondition(category!)
// Column(
// children: [
// _buildDefuListView()
// // if (mode == 0) ...[
// // _buildDefuListView()
// // ] else if (mode == 5) ...[
// // _buildListView(mode)
// // ]
// ],
// ),
),
),
),
],
),
),
drawer: Drawer(
child: ListView(
children: [
UserAccountsDrawerHeader(
accountName: Text("Gunjon Roy"),
accountEmail: Text("gunjon.cse#gmail.com"),
currentAccountPicture: CircleAvatar(
radius: 20,
backgroundImage: AssetImage("images/men's.png"),
child: Text("Edit"),
),
),
ListTile(
leading: Icon(Icons.shopping_cart),
title: Text("Carts"),
onTap: (){
print("hello world<<<<<<<<<<<<>>>>>>>>>>>>>>");
},
)
],
),
),
bottomNavigationBar: Container(
height: MediaQuery.of(context).size.height * 0.06,
color: Colors.white,
child: Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.03,
),
FlatButton(
onPressed: () {},
child: Text(
'Explore',
style: TextStyle(color: Color(0xFFfca903)),
)),
SizedBox(
width: MediaQuery.of(context).size.width * 0.15,
),
FlatButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>Cart()));
},
child: Icon(
Icons.add_shopping_cart,
color: Color(0xFFfca903),
)),
SizedBox(
width: MediaQuery.of(context).size.width * 0.12,
),
FlatButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>Profile()));
},
child: Icon(
Icons.perm_identity_outlined,
color: Color(0xFFfca903),
)),
],
),
),
);
}
Widget _buildListView(String mode){
// String? who;
// if(number==5){
// who="kids";
// }else if(number==16){
// who="boys";
// }else if(number==18){
// who="mens";
// }else if(number==21){
// who="girls";
// }else{
// who="";
// }
//var item = '';
final size=MediaQuery.of(context).size;
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('product').document(mode).collection(mode).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: Column(
children: [
CircularProgressIndicator(),
Text('Loading...',style: TextStyle(color: Colors.white),),
],
));
} else
return SingleChildScrollView(
child: ListView(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: snapshot.data!.documents.map((document){
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color(0xFFff9f36)
),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(
mode,
document['name'] ?? '',
document['details'] ?? '',
document['price'] ?? '',
document['imageUrl'] ?? ''
)));
},
child: ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//NetworkImage(),
Card(
elevation: 20,
color: Colors.white,
//BoxDecoration(color: Colors.black)
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
side:
BorderSide(color: Colors.black)),
child: Container(
height: MediaQuery.of(context).size.height * 0.35,
width: MediaQuery.of(context).size.width * 0.45,
child: Image(
image: NetworkImage(
document['imageUrl'] ?? '')),
),
),
Padding(
padding: const EdgeInsets.only(left: 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
document['name'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['details'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['price'] ?? '',
style: TextStyle(color: Colors.white),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.015,)
],
),
),
],
),
),
);
}).toList()),
);
}
);
// ListView.builder(
// scrollDirection: Axis.vertical,
// itemCount: number,
// itemBuilder: (BuildContext context, int index) {
// return Padding(
// padding: const EdgeInsets.only(bottom: 20),
// child: Container(
// decoration: BoxDecoration(
// color: Colors.grey,
// borderRadius: BorderRadius.circular(15)
// ),
// width: 50,
// height: 100,
// //child: SizedBox(width: 20,),
// ),
// );
// },
// );
}
Widget _buildDefuListView(var mode){
final size=MediaQuery.of(context).size;
return Column(
//crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Best Selling",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.white
),
),
SizedBox(width: size.width*.3,),
// ElevatedButton(
// style: ElevatedButton.styleFrom(
// primary: Colors.white
// ),
// onPressed: (){
//
// }, child: Text("See all",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// fontSize: 20,
// color: Colors.white
// ),
// )
// )
TextButton(
onPressed: (){
},
child: Text("See all",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white
),
)
),
],
),
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('product').document(mode).collection(mode).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(child: Column(
children: [
CircularProgressIndicator(),
Text('Loading...',style: TextStyle(color: Colors.white),),
],
));
} else
return SingleChildScrollView(
child: ListView(
physics: NeverScrollableScrollPhysics(),
//physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: snapshot.data!.documents.map((document){
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color(0xFFff9f36)
),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Details(
mode,
document['name'] ?? '',
document['details'] ?? '',
document['price'] ?? '',
document['imageUrl'] ?? ''
)));
},
child: ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//NetworkImage(),
Card(
elevation: 20,
color: Colors.white,
//BoxDecoration(color: Colors.black)
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(15),
),
side:
BorderSide(color: Colors.black)),
child: Container(
height: MediaQuery.of(context).size.height * 0.35,
width: MediaQuery.of(context).size.width * 0.45,
child: Image(
image: NetworkImage(
document['imageUrl'] ?? '')),
),
),
Padding(
padding: const EdgeInsets.only(left: 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
document['name'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['details'] ?? '',
style: TextStyle(color: Colors.white),
),
Text(
document['price'] ?? '',
style: TextStyle(color: Colors.white),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.015,)
],
),
),
],
),
),
);
}).toList()),
);
}
),
],
);
}
Widget _buildcondition(String mode){
if(mode=='women'){
return _buildListView(mode);
}
else if(mode=='men'){
return _buildListView(mode);
}
else if(mode=='Device'){
return _buildListView(mode);
}
else if(mode=='Kids'){
return _buildListView(mode);
}
else if(mode=='electronics'){
return _buildListView(mode);
}
else{
return _buildListView('women');
//_buildListView('women');
}
}
}

type 'Future<dynamic>' is not a subtype of type 'Route<Object>'

I got the the following error for below code. I was attempting to navigate to the next page. I was able to navigate just once and then I got the error mentioned above. Please do help me on this. I tried even using await but await is not supported for builder: (BuildContext context) => SubmitArticles()).
class UserSubmitOption extends StatefulWidget {
#override
_UserSubmitOptionState createState() => _UserSubmitOptionState();
}
class _UserSubmitOptionState extends State<UserSubmitOption> {
#override
Widget build(BuildContext dynamic) => MaterialApp(
debugShowCheckedModeBanner: false,
home:SafeArea (
child: Scaffold(
backgroundColor: Colors.indigo[800],
resizeToAvoidBottomInset: false,
appBar: AppBar(
toolbarHeight: 60,
backgroundColor: Colors.indigo[900],
automaticallyImplyLeading: false,
title: Text("What do you want to submit?",style:TextStyle(color:Colors.white,fontWeight:FontWeight.bold)),
centerTitle: true,
leading: IconButton(
icon: Icon(Icons.arrow_back,color:Colors.black,size:25,),
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => UserMenu())))),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(60.0),
child: Center(
child: Wrap(spacing: 50, runSpacing: 50.0, children: <Widget>[
GestureDetector(
onTap: () {
SubmitQuiz();
setState(() {
});
},
child: SizedBox(
width: 200.0,
height: 200.0,
child: Card(
color: Colors.indigo,
borderOnForeground:true,
shadowColor: Colors.white,
elevation: 20.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0)),
child: Center(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: Column(
children: <Widget>[
Icon(
Icons.vpn_key_outlined,size:60,color:Colors.black,
), // Image.asset("assets/todo.png",width: 64.0,),
SizedBox(
height: 7.0,
),
Text(
"Quiz",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 17.0,
),
),
SizedBox(
height: 5.0,
),
],
),
)),
),
)),
GestureDetector(
onTap: () async {Navigator.push(context,
MaterialPageRoute (
builder: (BuildContext context) => SubmitArticles())
);},
child: SizedBox(
width: 200.0,
height: 200.0,
child: Card(
color: Colors.indigo,
elevation: 20.0,
shadowColor:Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0)),
child: Center(
child: Padding(
padding: const EdgeInsets.all(45.0),
child: Column(
children: <Widget>[
Icon (
Icons.article_outlined,size:60,
),
// Image.asset("assets/note.png",width: 64.0,),
SizedBox(
height: 7.0,
),
Text(
"Articles",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 17.0),
),
SizedBox(
height: 5.0,
),
],
),
)),
),
)),
]),
),
),
],
),
),
)));
}
You are trying to access route in the wrong way
use instead:
Navigator.push(context,MaterialPageRoute(
builder : (context) => SubmitArticles())
);
i hope it work with you.
happy coding!

Screen is not closing on click on press of alert dialog in flutter

Hi I have designed a screen in flutter. I have AlertDialog on which I want to close the dialog and screen on pressing. Right now AlertDialog dismiss on press but screen is not closing.
Does anyone know how to do this ?
class ForgotPasswordScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return ForgotPasswordScreenState();
}
}
class ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
var emailController = new TextEditingController();
var authHandler = new Auth();
bool isLoading = false;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
color: Colors.white,
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(
child: isLoading
? Center(child: CircularProgressIndicator())
: new Container()),
],
),
new Row(
children: <Widget>[
new Expanded(
child: new Padding(
padding: const EdgeInsets.only(left: 40.0),
child: new Text(
"EMAIL",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.redAccent,
fontSize: 15.0,
),
),
),
),
],
),
new Container(
width: MediaQuery.of(context).size.width,
margin:
const EdgeInsets.only(left: 40.0, right: 40.0, top: 10.0),
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.redAccent,
width: 0.5,
style: BorderStyle.solid),
),
),
padding: const EdgeInsets.only(left: 0.0, right: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Expanded(
child: TextField(
controller: emailController,
textAlign: TextAlign.left,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'PLEASE ENTER YOUR EMAIL',
hintStyle: TextStyle(color: Colors.grey),
),
),
),
],
),
),
Divider(
height: 24.0,
),
new Container(
width: MediaQuery.of(context).size.width,
margin:
const EdgeInsets.only(left: 30.0, right: 30.0, top: 20.0),
alignment: Alignment.center,
child: new Row(
children: <Widget>[
new Expanded(
child: new FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
color: Colors.redAccent,
onPressed: () {
setState(() {
isLoading = true;
});
authHandler
.sendPasswordResetEmail(emailController.text)
.then((void nothing) {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
content: new Text(
"Password reset email has been sent."),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
setState(() {
isLoading = false;
});
}).catchError((e) => print(e));
},
child: new Container(
padding: const EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Expanded(
child: Text(
"FORGOT PASSWORD",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
],
),
),
],
)));
}
}
Ideally, you'll want to call pop more than once. One for the modal, another for the actual route.
There are a few ways to achieve this. But ideally you'll want to await the close of the dialog before triggering another close:
foo() async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
actions: [
new FlatButton(
child: new Text("OK"),
onPressed: () => Navigator.pop(context),
),
],
),
);
Navigator.pop(context);
}
This way, both the route and the modal can handle their close however they like.
This is how i did with mine
bool _logout = false;
and then at the start of build Widget
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
_onBackPressed(context);
return _logout;
},
child: Container(),
);
}
and the method _onBackPressed returns a custom dialog Class like so
void _onBackPressed(BuildContext c) async {
await showDialog(
barrierColor: CustomColors.darkGrey.withOpacity(0.8),
barrierDismissible: true,
context: context,
builder: (BuildContext context) {
return CustomDialogBox(
title: 'Logout',
description: 'Are you sure you want to logout?',
rightButtonText: 'Yes',
onPClick: () {
_logout = true;
if (_logout == true) {
Get.back();
}
},
onNClick: () {
_logout = false;
Get.back();
},
);
});
if (_logout == true) {
Get.back();
}
}
and my custom Dialog class is here
class CustomDialogBox extends StatefulWidget {
final String? title, description, leftButtonText, rightButtonText;
final VoidCallback? onPClick, onNClick;
final Image? image;
const CustomDialogBox({
Key? key,
this.title,
this.description,
this.leftButtonText,
this.rightButtonText,
this.image,
this.onPClick,
this.onNClick,
}) : super(key: key);
#override
_CustomDialogBoxState createState() =>
// ignore: no_logic_in_create_state
_CustomDialogBoxState(onPClick!, onNClick!);
}
class _CustomDialogBoxState extends State<CustomDialogBox> {
final VoidCallback onPClick, onNClick;
_CustomDialogBoxState(this.onPClick, this.onNClick);
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(Dimensions.BORDER_RADIUS_4),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: Container(
//height: 200,
padding: const EdgeInsets.only(
left: 10,
right: 0,
bottom: 10,
),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: CustomColors.darkGrey,
offset: const Offset(0, 30),
blurRadius: 20,
),
]),
child: Wrap(children: <Widget>[
dialogBody(context),
]),
),
);
}
Widget dialogBody(context) {
return Column(children: [
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Image.asset(
Images.LOGO,
height: MediaQuery.of(context).size.height * 0.035,
),
IconButton(
//padding: const EdgeInsets.all(0),
onPressed: () {
Get.back();
},
icon: const CircleAvatar(
radius: 12.5,
child: Icon(
Icons.close,
color: Colors.white,
),
backgroundColor: Colors.red,
),
),
]),
Padding(
padding: const EdgeInsets.only(
right: 10,
),
child: Column(children: [
//----//
customText(
text: widget.title ?? '',
fontFamily: 'black',
fontSize: 16,
),
//----//
const Space(0, 0.01),
//----//
customText(
text: widget.description ?? '',
fontSize: 14,
),
]),
),
//----//
const Space(0, 0.03),
//----//
Padding(
padding: const EdgeInsets.only(
right: 10,
),
child:
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
//----//
raisedButton(
text: widget.leftButtonText ?? 'Cancel',
fontFamily: 'roman',
height: 35,
width: 105,
buttonColor: CustomColors.red,
onClick: () {
return onNClick();
},
context: context,
),
//----//
raisedButton(
text: widget.rightButtonText ?? 'Okay',
fontFamily: 'roman',
height: 35,
width: 105,
buttonColor: CustomColors.green,
onClick: () {
return onPClick();
},
context: context,
),
//----//
]),
),
]);
}
}
the buttons and texts are custom so feel free to change them. and where you see Get.back(); is GetX code.. you can replace with Navigator.of(context).pop();
try this
showPop() async {
await showDialog(
context: context,
barrierDismissible: true,
builder: (context) => AlertDialog(
actions: [
new FlatButton(
child: new Text("Close"),
onPressed: () => Navigator.pop(context),
),
],
),
);
}

Categories

Resources