how to call a function in flutter from another page - function

I'm new to flutter and i was working on a small poc project. All I Want is that to call a function which is in second page from my first page using abutton click. here what i had done,
1st page
class Mainpage extends StatefulWidget {
#override
_MainpageState createState() => _MainpageState();
}
class _MainpageState extends State<Mainpage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: Padding(
padding: EdgeInsets.only(left: 12),
child: IconButton(
icon: Icon(Icons.menu,
color: Colors.grey[500],
size: 30,),
onPressed: () {
print('Click leading');
},
),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
Text('Basic AppBar'),
]
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.notifications,
color: Colors.grey[500],
size: 30,),
onPressed: () {
Navigator.pushNamed(context, '/notifications');
},
),
],
),
body:
Container(
padding: EdgeInsets.fromLTRB(10,10,10,0),
child: Column(
children:<Widget>[
Row(
children:<Widget>[
]),
SizedBox(height: 60),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children:<Widget>[
GestureDetector(
child: Image.asset('assets/cam.png',
height:90),
onTap: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
elevation: 16,
child: Container(
height: 180.0,
width: 330.0,
child: ListView(
children: <Widget>[
SizedBox(height: 20),
//Center(
Padding(
padding: const EdgeInsets.only(left:15.0),
child: Text(
"Add a Receipt",
textAlign: TextAlign.left,
style: TextStyle(fontSize: 24, color: Colors.black, fontWeight: FontWeight.bold),
),
),
// ),
SizedBox(height: 20),
FlatButton(
child: Text(
'Take a photo..',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 20),
),
onPressed: () {
});
i don't know want to give in the onpressed function at the end of the above code
and the 2nd page is as follow
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _selectedFile;
bool _inProcess = false;
Map data = {};
Widget getImageWidget() {
if (_selectedFile != null) {
return Image.file(
_selectedFile,
width: 350,
height: 650,
fit: BoxFit.cover,
);
} else {
return Image.asset(
"assets/splashlogo.png",
width: 350,
height: 650,
fit: BoxFit.cover,
);
}
}
getImage(ImageSource source) async {
this.setState((){
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
maxWidth: 1080,
maxHeight: 1080,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.black,
toolbarWidgetColor: Colors.white,
//toolbarTitle: "RPS Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.black,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false
),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
)
);
this.setState((){
_selectedFile = cropped;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
}
i needed to call getImage(ImageSource.camera); inside the my onpress function in the 1st page which points to the getimage function on second page.
can anyone help me with it..?

here add this in you 1st page in onpressed
Navigator.pushReplacementNamed(context,'/2ndpage',arguments: {
'pickerCode': "0",
});
and on the second page you do
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
data = ModalRoute.of(context).settings.arguments;
print(data);
if(data['pickerCode']=="0"){
getImage(ImageSource.camera);
}
});
}
this is a tricky thing but I think it will help you.

Use a GlobalKey.
GlobalKey<_MyHomePageState> globalImageKey = GlobalKey();
Change this:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}): super(key:key)
#override
_MyHomePageState createState() => _MyHomePageState();
}
when using MyHomePage:
MyHomePage(key: globalImageKey)
call:
globalImageKey.currentState.getImage(ImageSource.camera);

Related

Flutter: how integrate function in the "DropdownButton" class and pass value to the parent class

I am trying to integrate a child class (implementing DropdownButton with four values: 2, 4, 6, and 8) to a parent class which should show some content depending on the value chosen.
If user clicks on one of the drop down values ie: 2, a widget on the main class should display a container with blue colour. If user click on value 4 it should display a container with red colour and so on.
My thoughts went along these lines, implementing a simple method which is reading chosen value, calls the appropriate class (ClassTwo, ClassThree...) passing its content to the parent class but I am not sure how to do so. My renderWidget() function remains unused and fuller suggesting removing it.
Can anyone please help?
child class (DropdownMenuButton)
class VorschlageDropdownMenu extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<VorschlageDropdownMenu> {
List<ListItem> _dropdownItems = [
ListItem(1, "2"),
ListItem(2, "4"),
ListItem(3, "6"),
ListItem(4, "8"),
];
List<DropdownMenuItem<ListItem>> _dropdownMenuItems;
ListItem _selectedItem;
void initState() {
super.initState();
_dropdownMenuItems = buildDropDownMenuItems(_dropdownItems);
_selectedItem = _dropdownMenuItems[0].value;
}
List<DropdownMenuItem<ListItem>> buildDropDownMenuItems(List listItems) {
List<DropdownMenuItem<ListItem>> items = List();
for (ListItem listItem in listItems) {
items.add(
DropdownMenuItem(
child: Text(listItem.name),
value: listItem,
),
);
}
return items;
}
#override
Widget build(BuildContext context) {
return SizedBox(
child: Container(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: kWidgetBacgroundColor,
border: Border.all()),
child: DropdownButtonHideUnderline(
child: DropdownButton(
value: _selectedItem,
items: _dropdownMenuItems,
onChanged: (value) {
setState(() {
_selectedItem = value;
renderWidget() {
if (value == "2")
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => MenuForZwei(),
),
);
else if (value == "4")
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => MenuForVier(),
),
);
else if (value == "6")
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => MenuForSechs(),
),
);
else if (value == "8")
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => MenuForAcht(),
),
);
}
});
}),
),
),
);
}
}
class ListItem {
int value;
String name;
ListItem(this.value, this.name);
}
parental class which should display value chosen
class VorschlageZutaten extends StatelessWidget {
const VorschlageZutaten({
Key key,
this.renderWidget,
}) : super(key: key);
final Function renderWidget;
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 50, top: 20),
),
Text(
"Für ",
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (20.0),
fontWeight: FontWeight.w600,
),
),
Container(height: 40, child: VorschlageDropdownMenu()),
Text(
" Personen:",
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (20.0),
fontWeight: FontWeight.w600,
),
),
],
),
Container(
child: renderWidget(),
),
],
);
}
}
I think I've read all available documentation and reviewed all examples so I had to redesign the VorschlageDropdownMenu() class in order to achieve desired result. This is how the main class looks now:
class VorschlageDropdownMenu extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _VorschlageDropdownMenuState();
}
}
class _VorschlageDropdownMenuState extends State<VorschlageDropdownMenu> {
String ddValue;
#override
void initState() {
super.initState();
ddValue = "ZWEI";
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50.0),
child: AppBar(
elevation: 0,
backgroundColor: kWidgetBacgroundColor,
title: Column(
children: <Widget>[
Row(
children: <Widget>[
Text(
"Für ",
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (20.0),
fontWeight: FontWeight.w600,
),
),
Container(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: kWidgetBacgroundColor,
border: Border.all()),
child: DropdownButtonHideUnderline(
child: new DropdownButton(
iconSize: 0.0,
value: ddValue, //Default value
items: <DropdownMenuItem>[
new DropdownMenuItem(
value: "ZWEI",
child: new Text(
'ZWEI',
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (17.0),
fontWeight: FontWeight.w700,
),
),
),
new DropdownMenuItem(
value: "VIER",
child: new Text('VIER',
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (17.0),
fontWeight: FontWeight.w700,
),
),
),
new DropdownMenuItem(
value: "SECHS",
child: new Text('SECHS',
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (17.0),
fontWeight: FontWeight.w700,
),
),
),
new DropdownMenuItem(
value: "ACHT",
child: new Text('ACHT',
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (17.0),
fontWeight: FontWeight.w700,
),
),
),
],
onChanged: (value) {
ddValue = value;
setState(() {});
},
),
),
),
Text(
" Personen:",
style: TextStyle(
color: kPrimaryHeaderColor.withOpacity(0.6),
fontSize: (20.0),
fontWeight: FontWeight.w600,
),
),
],
),
],
),
),
),
body: ListederMenus(),
);
}
Widget ListederMenus() {
if (ddValue == "ZWEI") {
return Center(child: MenuForZwei());
} else if (ddValue == "VIER") {
return Center(child: MenuForVier());
} else if (ddValue == "SECHS") {
return Center(child: MenuForSechs());
} else if (ddValue == "ACHT") {
return Center(child: MenuForAcht());
}
}
}```
and **MenuForZwei()** and other classes with different colours:
```class MenuForZwei extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
);
}
}```

How to improve the performance of my app in flutter

I am building an app called LiveTv which is an app which recommends videos as per varied interests.The code I have written is causing serious lags and as I am proceeding more and more in this app it is becoming next to inoperable.I have included the video of the same in this link https://youtu.be/YQp3E3Lukfk
What I have done is make the call async and I have used a ternary operator wherein which under it loads a circular progress indicator is shown.But it doesn't seems to work only
I have included the code which is the one which is controlled by the bottom navigation bar.The services part of it is not included as its function is only to load the data or the object,but I will include one or two so that you may understand and I dont want to make this question very long
class LiveTvHomePage extends StatefulWidget {
final String title;
LiveTvHomePage({
this.title,
});
#override
_LiveTvHomePageState createState() => _LiveTvHomePageState();
}
class _LiveTvHomePageState extends State<LiveTvHomePage> {
//GlobalKey<ScaffoldState> _drawerKey = GlobalKey<ScaffoldState>();
#override
void initState() {
// TODO: implement initState
super.initState();
handleScroll(); // function which is responsible for updating the isScrollingDown variable whenever the user scrolls down
_services();
setState(() {
_isLoading = false;
});
}
_loadingImage() {
return CircularProgressIndicator();
}
_services() {
Services.loadDataForMovieId().then((movieIdList) {
setState(() {
_homeBannerObjectMovieIdList = movieIdList;
});
});
Services.loadDataForMovieIdofPopularMovieSection().then((movieIdList) {
setState(() {
_popularMoviesMovieId = movieIdList;
});
});
Services.loadDataForPopularTvShowSection().then((homePageSeriesPosterList) {
setState(() {
_seriesData = homePageSeriesPosterList;
});
});
Services.loadDataForMusicSection().then((musicList) {
setState(() {
_musicCategories = musicList;
});
});
Services.loadDataForPlaylistTitle().then((title) {
setState(() {
_musicPlaylistThemeName = title;
});
});
Services.loadDataForPopularNewsChannelsNames().then((nameList) {
setState(() {
_popularNewsChannelNames = nameList;
});
});
Services.loadDataForPopularNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_popularNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_liveNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsNames().then((nameList) {
setState(() {
_liveNewsChannelNames = nameList;
});
});
Services.loadDataForPicOfLatestNews().then((nameList) {
setState(() {
_latestNewsProfilePics = nameList;
});
});
Services.loadDataForOfLatestNewsTitle().then((nameList) {
setState(() {
_latestNewsNewsTitle = nameList;
});
});
Services.loadDataForOfLatestNewsDescription().then((nameList) {
setState(() {
_latestNewsDescription = nameList;
});
});
}
_buildBody(var boxHeight, List<String> youtubeIdUrls) {
return Column(
children: <Widget>[
Stack(
children: <Widget>[
_buildPageView(boxHeight, youtubeIdUrls),
_buildCircleIndicator(youtubeIdUrls),
],
),
],
);
}
_buildPageView(var boxHeight, List<String> youtubeIdUrls) {
return Container(
color: Colors.black87,
height: boxHeight,
child: PageView.builder(
itemCount: 8,
controller: _pageController,
itemBuilder: (BuildContext context, int index) {
try {
// HomeBanner homeBanner=_homeBannelList[index];
return FadeInImage.assetNetwork(
image:
'https://img.youtube.com/vi/${youtubeIdUrls[index].substring(8)}/0.jpg',
placeholder: 'assets/loading.gif',
fit: BoxFit.fill,
);
} catch (e) {
return CircularProgressIndicator();
}
//before return Image.network('https://img.youtube.com/vi/${videoIdOfUrlList[index]}/0.jpg',fit: BoxFit.fill,);
},
onPageChanged: (int index) {
_currentPageNotifier.value = index;
}),
);
}
_buildCircleIndicator(List<String> youtubeIdUrls) {
return Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: CirclePageIndicator(
itemCount: 8,
currentPageNotifier: _currentPageNotifier,
),
),
);
}
Widget imageDisplayed(String picUrl) {
return Row(
children: <Widget>[
const SizedBox(
width: 10,
),
CircleAvatar(
backgroundImage: NetworkImage(picUrl),
radius: MediaQuery.of(context).size.height * 0.08,
backgroundColor: Colors.black,
),
const SizedBox(
width: 10,
),
],
);
}
Widget HorizontalListViewWitCircularCards(
String title, List<String> urlList, List<String> nameList) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.32,
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.07,
color: Colors.black,
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text(
title,
style: TextStyle(fontSize: 16, color: Colors.white),
),
),
),
Container(
height: MediaQuery.of(context).size.height * 0.23,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _popularNewsChannelNames.length,
itemBuilder: (BuildContext context, int index) => Card(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.symmetric(),
child: Column(
children: <Widget>[
imageDisplayed(urlList[index]),
const SizedBox(
height: 13,
),
Text(
nameList[index],
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
),
],
),
);
}
Widget HorizontalGridViewOfCardsofGradientColor(int count, List<String> lst) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.125 * count,
child: GridView.count(
scrollDirection: Axis.horizontal,
crossAxisCount: count,
shrinkWrap: true,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: List.generate(20, (index) {
return Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
borderRadius: BorderRadius.all(Radius.circular(15)),
gradient: LinearGradient(colors: colorsForCardinMusicPage[index]),
),
child: Center(
child: Text(
lst[index],
),
),
);
}),
),
);
}
Widget HorizontalGridViewOfCardsofGradientColorWithtitle(
int count, String title) {
return Column(
);
}
Widget HorizontalListViewOfButtons(List moviesPageButtonNames) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.13,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: moviesPageButtonNames.length,
itemBuilder: (BuildContext context, int index) => Row(
children: <Widget>[
SizedBox(
width: 7,
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.grey)),
color: Colors.grey[800],
textColor: Colors.white,
onPressed: () {},
child: Text(moviesPageButtonNames[index]),
),
SizedBox(
width: 10,
)
],
),
),
);
}
Widget NewsPageOfBottomNavigator() {
ServicesForNewsPage.loadObjectList().then((newsPageObject) {
_newsPage = newsPageObject;
});
for (var obj in _newsPage.liveChannels) {
_newsPageLiveNewsUrls.add(obj.publisherProfilePic);
_newsPageChannelName.add(obj.publisherName);
}
// print("_newsPageLiveNewsUrls");
// print(_newsPageLiveNewsUrls);
// print("_newsPageLiveNewsNames");
// print(_newsPageChannelName);`
for (var obj in _newsPage.news) {
_newsPagePopularNewsChannelUrls.add(obj.publishers.profilePicUrl);
_newsPagePopularNewsChannelNames.add(obj.publishers.fullName);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWithoutViewAllForLiveNewsChannels(
"Watch Live", _newsPageLiveNewsUrls, _newsPageChannelName),
HorizontalListViewWitCircularCards("Popular News Channel",
_newsPagePopularNewsChannelUrls, _newsPagePopularNewsChannelNames),
VerticalListView(_newsPagePopularNewsChannelNames, true),
],
);
}
Widget LifeStylePageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Lifestyle channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget SportsPageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Sports channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget returnToTopButton() {
return Visibility(
visible: _showButton,
child: FlatButton(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 7, 0, 0),
child: Text(
"^",
style: TextStyle(color: Colors.white, fontSize: 27),
),
),
Text(
" Return to top",
style: TextStyle(color: Colors.white),
),
],
),
onPressed: () {
_scrollController.animateTo(0,
duration: Duration(milliseconds: 500), curve: Curves.easeInOut);
},
color: Colors.red,
),
);
}
void showFloationButton() {
setState(() {
_showButton = true;
});
}
void hideFloationButton() {
setState(() {
_showButton = false;
});
}
void handleScroll() async {
// or something else..
_scrollController.addListener(() {
double currentScroll = _scrollController.position.pixels;
double delta = MediaQuery.of(context).size.height;
// print("Current scroll position is ..........$currentScroll");
// print("delta pixel is ..........$delta");
if (currentScroll >= delta) {
showFloationButton();
} else if (currentScroll <= delta) {
hideFloationButton();
}
});
}
#override
void dispose() {
// TODO: implement dispose
_scrollController.removeListener(() {});
super.dispose();
}
#override
Widget build(BuildContext context) {
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
return _isLoading
? _loadingImage()
: Scaffold(
// key: _drawerKey,
appBar: AppBar(
automaticallyImplyLeading: false,
leading: Icon(
Icons.live_tv,
color: Colors.amber,
),
backgroundColor: Colors.black,
title: Text(
widget.title,
style: TextStyle(fontSize: 17, color: Colors.amber),
),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(
MaterialCommunityIcons.xbox_controller_menu,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DrawerWidget()),
);
},
)
],
),
body: SafeArea(
child: SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
),
),
drawer: Drawer(),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.black,
showUnselectedLabels: true,
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
fixedColor: Colors.amber,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
// Icon(
// FontAwesome.facebook_square,
// color: Colors.amber,
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
MaterialCommunityIcons.video_vintage,
),
title: Text(
'Movies',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.live_tv),
title: Text(
'Tv shows',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.music_video),
title: Text(
'Music',
),
),
// BottomNavigationBarItem(
// backgroundColor: Colors.black,
// icon: Icon(Icons.dehaze),
// title: Text(
// 'More',
// ),
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.radio),
title: Text(
'News',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
FontAwesome.heartbeat,
),
title: Text(
'LifeStyle',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
Ionicons.md_football,
),
title: Text(
'Sports',
),
),
],
),
);
}
}
The services class seems like this in most cases:
class ServicesForNewsPage {
static const String url =
"https://livetvapi.apyhi.com/api/v3/home?pageLocation=News&countries=IN&app_version=13&"
"user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";
static Future<NewsPage> loadObjectList() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
// print("response is there for news Page");
final newsPageObjectList = newsPageFromJson(res.body);
return newsPageObjectList;
} else {
print("no response");
return null;
}
}
}
I am quite new to flutter and things are bit hazy as to how to improve the response time.
You're question is quite broad. Have you tried playing with the DevTools?
I don't know the full code of your project, but I think I see that you are initializing all pages every time the build() of your homepage is called.
Consider changing this:
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
to something either 1.:
if (_selectedIndex == 0) {
wdgs_option = HomePageForBottomNavigator();
} else if (hi == _selectedIndex) {
wdgs_option = MoviesPageForBottomNavigator();
} else if (){}
or to 2.:
List<int Function()> wdgs_option = [
() => HomePageForBottomNavigator(),
() => MoviesPageForBottomNavigator(),
() => ...
];
int val = c[1]();
and in that case
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
)
to
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option[_selectedIndex](),
)

Flutter GestureDetector is not working on functions

class GridDashboard extends StatefulWidget {
final Function onTap;
const GridDashboard({Key key, this.onTap}) : super(key: key);
#override
_GridDashboardState createState() => _GridDashboardState();
}
class _GridDashboardState extends State<GridDashboard> {
Items item1 = new Items(
title: 'Books',
img: 'assets/images/open-book.png',
onTap: () {
Books();
});
Items item2 = new Items(
title: 'Audio',
img: 'assets/images/headphones.png',
onTap: () => print('Audio')); // it works when I just print smth
Items item3 = new Items(
title: 'Videos',
img: 'assets/images/play-button.png',
onTap: () {
Videos();
});
#override
Widget build(BuildContext context) {
List<Items> myList = [item1, item2, item3];
return Flexible(
child: GridView.count(
childAspectRatio: 1.0,
padding: EdgeInsets.only(left: 30, right: 20, top: 220),
crossAxisCount: 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
children: myList.map((data) {
return GestureDetector(
onTap: data.onTap, // this line is not working
child: Container(
decoration: BoxDecoration(
color: Color(0xFFFFFFFF),
borderRadius: BorderRadius.circular(35),
boxShadow: [
BoxShadow(
color: Color(0xFF373234),
blurRadius: 6.0,
offset: Offset(0, 2),
),
],
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(data.img, width: 45),
SizedBox(height: 15),
Text(
data.title,
style: GoogleFonts.openSans(
textStyle: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
);
}).toList(),
),
);
}
}
class Items {
String title;
String img;
Function onTap;
Items({this.img, this.title, this.onTap});
}
Hi people.
I am building an android app. The above code is for a dashboard (menu) section of my code. The GestureDetector onTap function is not working when I want it to go to another screen. But it works if I just want to print out smth. If you know how to solve this issue can you please help here ?
Thank you.
You can use named routes.
For Example :
Add the routes to you MaterialApp
void main() {
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/books': (context) => Books(),
'/videos': (context) => Videos(),
},
));
}
Change onTap to go to the specific page
onTap: () {
Navigator.pushNamed(context, '/books');
});
Make changes to the widgets accordingly.

Flutter switch widget- I ony want it to execute the function when it's active, what to do?

I have a problem with the switch widget in flutter. I only want to execute the onChanged function when I activate it but every time I click on the switch even when it's not active, it executes the function and I have the popup menu that appears.
new Switch(
value: false,
onChanged: (bool isOn) {
if(isOn){
setState(() {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
key: _alertDialogKey,
contentPadding: EdgeInsets.only(left: 25, right: 25),
title: Center(
child: Text("Choisissez une filiale")
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20.0)),
),
content: Container(
height: 350,
width: 300,
child: ListView.builder(
itemCount: litems.length,
itemBuilder: (_, index) {
return RaisedButton(
onPressed: () => popupAppuieSurUneFiliale( index)
//changementAffiliation(litems[index]),
child: Text(
litems[index],
style: TextStyle(color: Colors.white),
),
color: Colors.black,
);
}
),
),
actions:[
RaisedButton(
child: Text("Annuler",),
onPressed: (){
Navigator.of(context).pop();
},
color: Colors.blue,
),
]
);
}
);
});
} else(){
};
}
);
Demo
You can copy paste run full code below
You can declare a bool _isOn and set to false and then in onChanged change value
code snippet
bool _isOn = false;
...
Switch(
value: _isOn,
onChanged: (bool isOn) {
setState(() {
_isOn = isOn;
});
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<String> litems = ["test"];
bool _isOn = false;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: _isOn,
onChanged: (bool isOn) {
setState(() {
_isOn = isOn;
});
if (isOn) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
//key: _alertDialogKey,
contentPadding:
EdgeInsets.only(left: 25, right: 25),
title:
Center(child: Text("Choisissez une filiale")),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0)),
),
content: Container(
height: 350,
width: 300,
child: ListView.builder(
itemCount: litems.length,
itemBuilder: (_, index) {
return RaisedButton(
onPressed: () => null,
//changementAffiliation(litems[index]),
child: Text(
litems[index],
style: TextStyle(color: Colors.white),
),
color: Colors.black,
);
}),
),
actions: [
RaisedButton(
child: Text(
"Annuler",
),
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blue,
),
]);
});
} else
() {};
}),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

I implemented method for check the users permission even thought i got error message "MissingPluginException" in flutter?

I implemented method for checkPermissionStatus even though, I got an error message, Unhandled Exception: MissingPluginException(No implementation found for method checkPermissionStatus on channel flutter.baseflow.com/permissions/methods)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sampletestingpro/Pages/Firstpage.dart';
import 'package:custom_switch/custom_switch.dart';
class Clockinout extends StatefulWidget {
#override
_ClockinoutState createState() => _ClockinoutState();
}
class _ClockinoutState extends State<Clockinout> {
bool location= false;
GoogleMapController _controller;
Position position;
Widget _child;
Future<void> getPermission() async{
PermissionStatus permission=await PermissionHandler()
.checkPermissionStatus(PermissionGroup.location);
if(permission==PermissionStatus.denied)
{
await PermissionHandler()
.requestPermissions([PermissionGroup.locationAlways]);
}
var geolocator=Geolocator();
GeolocationStatus geolocationStatus=await geolocator.checkGeolocationPermissionStatus();
switch(geolocationStatus)
{
case GeolocationStatus.disabled:
showToast('Disabled');
break;
case GeolocationStatus.restricted:
showToast('Restricted');
break;
case GeolocationStatus.denied:
showToast('Denid');
break;
case GeolocationStatus.unknown:
showToast('Unknown');
break;
case GeolocationStatus.granted:
showToast('Granded');
_getCurrentLocation();
break;
}
}
void showToast(message)
{
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0,
);
}
void _getCurrentLocation() async
{
Position res=await Geolocator().getCurrentPosition();
setState(() {
position=res;
_child=_mapWidget();
});
}
#override
void initState() {
getPermission();
super.initState();
}
Widget _mapWidget()
{
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: LatLng(position.latitude,position.longitude),zoom:20.0),
onMapCreated:(GoogleMapController controller)
{
_controller=controller;
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
'',
style: TextStyle(color: Colors.black),
),
),
backgroundColor: Colors.white,
elevation: 0.0,
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
icon: Icon(
Icons.chevron_left,
color: Colors.black,
),
onPressed: () {
print('back');
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) => Firstpage()));
},
),
),
),
body: SingleChildScrollView(
child:Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Hentry Nixon',style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,),),
CustomSwitch(
activeColor: location == false ? Colors.red : Colors.green,
value: location,
onChanged: (value) {
print("VALUE : $value");
setState(() {
location = value;
});
},
),
],
),
Row(
children: <Widget>[
Text('2020.02.14',style: TextStyle(color: Colors.black45,),),
Text(''),
],
),
SizedBox(height: 50.0,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Current Project/Task',style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 20.0),),
Text('Harmony',style: TextStyle(color: Colors.black,fontSize: 20.0),),
],
),
Divider(
thickness: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Current Activity',style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 20.0),),
Text('Testing',style: TextStyle(color: Colors.black,fontSize: 20.0),),
],
),
Divider(
thickness: 2,
),
Container(
height: 350.0,
color: Colors.yellow,
child: _child,
),
],
),
),
),
),
);
}
}
Are there any way to implemented check permission and get current location
This is working for me
flutter run
or
flutter clean
Sometime it caused by AndroidManifest.xml if you implemented wrong meta-data or activity etc...
When I updated all of plugins by force , I faced that kind of MissingPluginException error . Because I m using old version of Facebook login meta-data and activity in AndroidManifest.xml . After fixed that everything is fine.
I have stopped running completely, exit app and restart the run
click on stop button, refer below