showModalBottomSheet rounded corner - flutter

I am facing strange issue in showModalBottomSheet. Rounded corner is not working. Please see the code. But ff I add the Text('Title') before Expanded widget, it is showing rounded corner.
But I can't add the title here because DownloadedDharmaSongScreen has AppBar.
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(_radius),
topRight: Radius.circular(_radius),
),
),
builder: (BuildContext context) {
return DraggableScrollableSheet(
initialChildSize: 0.9,
expand: false,
builder: (context, scrollController) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: DownloadedDharmaSongScreen(
controller: scrollController,
destinationFavourite: widget.destinationFavourite,
sourceFavourite: favourite,
socialMode: widget.socialMode,
),
),
const SizedBox(
height: 60,
)
],
);
},
);
},
);
DownloadedDharmaSongScreen
class DownloadedDharmaSongScreen extends StatefulWidget {
static const routeName = '/downloaded_dharma_song';
final ScrollController? controller;
final Favourite? destinationFavourite;
final Favourite? sourceFavourite;
final SocialMode socialMode;
const DownloadedDharmaSongScreen({
Key? key,
this.controller,
this.destinationFavourite,
this.sourceFavourite,
required this.socialMode,
}) : super(key: key);
#override
State<DownloadedDharmaSongScreen> createState() =>
_DownloadedDharmaSongScreen();
}
class _DownloadedDharmaSongScreen extends
State<DownloadedDharmaSongScreen> {
List<FavouriteSong> favouriteSongs = [];
List<FavouriteSong> selectedFavouriteSongs = [];
bool isSelected = false;
_loadDownloadFiles() async {
BlocProvider.of<FavouriteSongBloc>(context).add(
GetAllDownloadedSongsByFavouriteId(
favouriteId: widget.sourceFavourite!.id!));
}
#override
void initState() {
super.initState();
_loadDownloadFiles();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
centerTitle: true,
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0,
title: AutoSizeText(
widget.sourceFavourite!.name,
style: Theme.of(context).appBarTheme.titleTextStyle,
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(
Icons.arrow_back,
color: Theme.of(context).primaryIconTheme.color!,
),
),
actions: [
Container(
padding: const EdgeInsets.only(left: 10, right: 10),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
CupertinoButton(
minSize: double.minPositive,
padding: const EdgeInsets.only(right: 5),
child: Icon(Icons.done,
color: selectedFavouriteSongs.isNotEmpty
? Theme.of(context).primaryIconTheme.color!
: Theme.of(context).disabledColor),
onPressed: selectedFavouriteSongs.isNotEmpty
? () {
BlocProvider.of<FavouriteSongBloc>(context).add(
AddSelectedSongs(
favourite: widget.destinationFavourite!,
favouriteSongs: selectedFavouriteSongs,
socialMode: widget.socialMode));
}
: null,
),
],
),
)
],
),
body: BlocListener<FavouriteSongBloc, FavouriteSongState>(
listener: (context, state) {
if (state is SelectedFavouriteSuccess) {
Navigator.of(context).pop();
}
},
child: BlocBuilder<FavouriteSongBloc, FavouriteSongState>(
builder: (context, state) {
if (state is SongError) {
return const SomethingWentWrongScreen();
} else if (state is DownloadedSongListLoaded) {
if (state.favouriteSongs.isEmpty) {
return const NoResultFoundScreen(
title: 'သိမ်းထားသေားတရားတော်များ မရှိသေးပါ။',
subTitle:
'ကျေးဇူးပြု၍ တရားတော်များကို အစီအစဉ်စာရင်းထဲသို့ ထည့်ပါ။',
);
}
favouriteSongs = state.favouriteSongs;
return ListView.separated(
separatorBuilder: (BuildContext context, int index) =>
const Divider(height: 1),
itemCount: state.favouriteSongs.length,
itemBuilder: (_, int index) {
return Material(
child: ListTile(
minLeadingWidth: 0,
onTap: () {
setState(() {
favouriteSongs[index].isSelected =
!favouriteSongs[index].isSelected;
if (favouriteSongs[index].isSelected == true) {
selectedFavouriteSongs.add(favouriteSongs[index]
.copyWith(isSelected: true));
} else if (favouriteSongs[index].isSelected ==
false) {
selectedFavouriteSongs.removeWhere((element) =>
element.id == favouriteSongs[index].id);
}
});
},
title: TitleWidget(
favouriteSong: favouriteSongs[index],
),
subtitle:
SubTitleWidget(favouriteSong: favouriteSongs[index]),
trailing: favouriteSongs[index].isSelected
? Icon(
Icons.check_circle,
color: Theme.of(context).primaryColor,
)
: const Icon(Icons.check_circle_outline),
),
);
},
);
}
return const CircularProgressIndicatorWidget();
},
),
),
);
}
}

You can wrap DraggableScrollableSheet with ClipRRect with providing borderRadius.
builder: (BuildContext context) {
return ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(_radius),
topRight: Radius.circular(_radius),
),
child: DraggableScrollableSheet(
This issue is coming from builder inner views, here it is from DownloadedDharmaSongScreen, You can also wrap it with ClipRRect instead of using it on builder.
builder: (context, scrollController) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(_radius),
topRight: Radius.circular(_radius),
),
child:DownloadedDharmaSongScreen(

Related

Flutter : how to change text data by bottomSheet?

I want to change my text, after selecting by bottomsheet text is not changing when i am refreshing then my text is changing.
how to fix this issue.
This is my code.
import 'package:flutter/material.dart';
import '../../../Utils/GlobalColor/global_color.dart';
import '../../../Utils/GlobalTextStyles/global_text_styles.dart';
class NonVegPizzaPage extends StatefulWidget {
const NonVegPizzaPage({Key? key}) : super(key: key);
#override
State<NonVegPizzaPage> createState() => _NonVegPizzaPageState();
}
class _NonVegPizzaPageState extends State<NonVegPizzaPage> {
String itemSize = "Regular";
List itemSizes = [];
#override
void initState() {
super.initState();
itemSizes = [
{
"sizes": "Regular",
},
{
"sizes": "Medium",
},
{
"sizes": "Large",
},
];
}
sizeBottomSheet() {
showModalBottomSheet(
barrierColor: Colors.transparent,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
),
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState1) {
return Container(
decoration: BoxDecoration(
color: MyColor.whiteColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
boxShadow: [
BoxShadow(
color: MyColor.greyColor.withOpacity(0.8),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 0), // changes position of shadow
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding:
const EdgeInsets.only(left: 43.0, top: 10, bottom: 11),
child: Text(
"Select Size",
style: textStyleWith14500(MyColor.blackColor2),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: itemSizes.length,
itemBuilder: (_, index) {
return Padding(
padding: EdgeInsets.only(
top: 0,
),
child: InkWell(
onTap: () {
Navigator.pop(context);
setState1(() {
itemSize = itemSizes[index]["sizes"];
});
print(itemSize);
},
child: Container(
margin: EdgeInsets.only(left: 2, right: 2),
height: 36,
width: double.infinity,
color: itemSize == itemSizes[index]["sizes"]
? MyColor.lightBlueColor
: MyColor.whiteColor,
child: Padding(
padding:
const EdgeInsets.only(left: 43.0, top: 10),
child: Text(
"${itemSizes[index]["sizes"]}",
style:
textStyleWith12400(MyColor.blackColor3),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
);
}),
],
),
);
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: Column(crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("$itemSize"), // here
SizedBox(height: 20,),
InkWell(
onTap: () {
sizeBottomSheet();
},
child: Container(
color: Colors.red,
height: 44,
width: 150,
child: Center(child: Text("show bottomSheet")),
),
)
],
),
),
),
);
}
}
showModalBottomSheet is a future method, you can await to close it and then call setState to update the main ui.
sizeBottomSheet() async {
final result = await showModalBottomSheet(
....
onTap: () {
Navigator.pop(context, itemSizes[index]["sizes"]);
.......
//end of showModalBottomSheet
if (result != null) {
itemSize = result;
setState(() {});
}
Or you can do
child: InkWell(
onTap: () {
setState1(() {
itemSize = itemSizes[index]["sizes"];
});
setState(() {});//updating the parent
Navigator.pop(context);
},

How to get back a value from a customly created widget in Flutter

I am showing a showModalBottomSheet using a function. I want that as soon as it closes, value of a variable should change. I wanted to change value of two variables, but I am not able to change for even one. Please help me with this. I tried to make my own onChanged and also tried to return the value using function, but nothing happens.
This is the function, please scroll to the last of it and check out the onTap function and return.
String showChapterSelectionSheet(
BuildContext context,
List<ChapterModel> chapter_list,
String chapter_name,
final Function(String) onChapterChanged) {
String retValue = chapter_name;
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
elevation: 0,
isScrollControlled: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20)),
),
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context,
StateSetter setState /*You can rename this!*/) {
return makeDismissible(
context,
child: DraggableScrollableSheet(
initialChildSize: 0.81,
minChildSize: 0.5,
maxChildSize: 0.81,
builder: (_, controller) => Container(
padding: EdgeInsets.all(getProportionateScreenWidth(25)),
height: getProportionateScreenWidth(600),
decoration: BoxDecoration(
color: backgroundColor2,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(
top: getProportionateScreenHeight(32),
bottom: getProportionateScreenHeight(16)),
child: Text(
AppLocalizations.of(context)!.chapters,
style: Theme.of(context)
.textTheme
.headline2!
.apply(color: Colors.white),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
controller: controller,
itemCount: chapter_list.length,
itemBuilder: (_, index) {
return GestureDetector(
child: Padding(
padding: EdgeInsets.only(
top: getProportionateScreenHeight(8)),
child: Card(
child: Container(
height: getProportionateScreenHeight(56),
width: getProportionateScreenWidth(341),
decoration: BoxDecoration(
border: Border.all(color: cardColor),
color: chapter_list[index].chapter_name! ==
chapter_name
? backgroundColor
: cardColor,
),
child: Padding(
padding: EdgeInsets.all(0),
child: Center(
child: Row(
children: [
Container(
width:
getProportionateScreenWidth(
32),
child: chapter_list[index]
.chapter_name! ==
chapter_name
? Icon(
Icons.check,
color: brandYellow,
)
: SizedBox()),
Text(
"Chapter ${chapter_list[index].position!}: ",
style: Theme.of(context)
.textTheme
.bodyText2!
.apply(color: brandYellow),
),
Expanded(
child: Text(
chapter_list[index]
.chapter_name!,
style: Theme.of(context)
.textTheme
.bodyText2!
.apply(
color: chapter_list[
index]
.chapter_name! ==
chapter_name
? tertiaryTextColor
: primaryTextColor)),
),
],
),
),
),
),
),
),
onTap: () {
onChapterChanged(chapter_list[index].chapter_name!);
setState(() {
retValue = chapter_list[index].chapter_name!;
});
Navigator.pop(context);
},
);
},
),
),
],
),
),
),
);
},
);
},
);
return retValue;
}
And I am accessing it here -
return InkWell(
onTap: () async {
if(dataList.isNotEmpty) {
chapterName.value = showChapterSelectionSheet(
context,dataList,chapterName.value,(val) {
setState(() {
chapterName.value = val;
print("Val is - $val");
});
}
);
}
},
child: .....
);
In the above InkWell, the print statement is working fine but value is not changing.
And I want to update and use the value here -
child: ValueListenableBuilder(
valueListenable: chapterName,
builder: (context, String val, Widget? child) {
return Text(
val,
style: TextStyle(
color: Colors.white,
fontSize: 15,
),
);
},
),
It is possible you are just missing await before await showModalBottomSheet(..).
You can follow this simplified snippet.
class BVChange extends StatefulWidget {
const BVChange({Key? key}) : super(key: key);
#override
State<BVChange> createState() => _BVChangeState();
}
class _BVChangeState extends State<BVChange> {
String var1 = "Old", var2 = "old1";
Future<String> _showDialog(String v) async {
double _sliderValue = 0.0;
await showModalBottomSheet(
context: context,
builder: (_) {
return StatefulBuilder(
builder: (context, sbSate) => Column(
children: [
Text(_sliderValue.toString()),
Slider(
value: _sliderValue,
onChanged: (sval) {
sbSate(() {
_sliderValue = sval;
});
}),
],
),
);
});
return _sliderValue.toString();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
GestureDetector(
onTap: () async {
final data = await _showDialog(var1);
setState(() {
var1 = data;
});
},
child: Text("var1 : $var1")),
GestureDetector(
onTap: () async {
final data = await _showDialog(var2);
setState(() {
var2 = data;
});
},
child: Text("var 2 : $var2"),
),
],
),
);
}
}

Adding filter button to different screens

I have a working filter button in search page of my app
I need to add it as floating button in other pages such as category, view all products etc
Here is the working filter button code for searchscreen.
class SearchProductWidget extends StatelessWidget {
final bool isViewScrollable;
final List<Product> products;
SearchProductWidget({this.isViewScrollable, this.products});
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
child: Column(
children: [
Row(
children: [
Expanded(
child: Text(
'Search result for \"${Provider.of<SearchProvider>(context).searchText}\" (${products.length} items)',
style: titilliumRegular.copyWith(
fontSize: Dimensions.FONT_SIZE_DEFAULT),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
InkWell(
onTap: () => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (c) => SearchFilterBottomSheet()),
child: Container(
padding: EdgeInsets.symmetric(
vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL,
horizontal: Dimensions.PADDING_SIZE_SMALL),
decoration: BoxDecoration(
color: ColorResources.getLowGreen(context),
borderRadius: BorderRadius.circular(5),
border: Border.all(
width: 1, color: Theme.of(context).hintColor),
),
child: Row(children: [
///Image.asset(Images.filter_image, width: 10, height: 10, color: ColorResources.getPrimary(context)),
SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
Text('Filter'),
]),
),
),
],
),
SizedBox(height: Dimensions.PADDING_SIZE_SMALL),
Expanded(
child: StaggeredGridView.countBuilder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.all(0),
crossAxisCount: 2,
itemCount: products.length,
//shrinkWrap: true,
staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
itemBuilder: (BuildContext context, int index) {
return ProductWidget(productModel: products[index]);
},
),
),
],
),
);
}
}
I'm trying to create a floating action button to work as a filter in different screens
Here is one of the screen which I need the filter button working-
class AllProductScreen extends StatelessWidget {
final ScrollController _scrollController = ScrollController();
final ProductType productType;
AllProductScreen({#required this.productType});
// Future<void> _loadData(BuildContext context, bool reload) async {
// String _languageCode = Provider.of<LocalizationProvider>(context, listen: false).locale.countryCode;
// await Provider.of<BrandProvider>(context, listen: false).getBrandList(reload, context);
// await Provider.of<ProductProvider>(context, listen: false).getLatestProductList('1', context, _languageCode, reload: reload);
//
//
//
// }
#override
Widget build(BuildContext context) {
// _loadData(context, false);
return Scaffold(
backgroundColor: ColorResources.getHomeBg(context),
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Provider.of<ThemeProvider>(context).darkTheme
? Colors.black
: Theme.of(context).primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(5),
bottomLeft: Radius.circular(5))),
leading: IconButton(
icon:
Icon(Icons.arrow_back_ios, size: 20, color: ColorResources.WHITE),
onPressed: () => Navigator.of(context).pop(),
),
title: Text(
productType == ProductType.FEATURED_PRODUCT
? 'Featured Product'
: 'Latest Product',
style: titilliumRegular.copyWith(
fontSize: 20, color: ColorResources.WHITE)),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (c) => SearchFilterBottomSheet()),
icon: const Icon(Icons.filter_list),
label: const Text('Filter'),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: SafeArea(
child: RefreshIndicator(
backgroundColor: Theme.of(context).primaryColor,
onRefresh: () async {
// await _loadData(context, true);
return true;
},
child: CustomScrollView(
controller: _scrollController,
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
child: ProductView(
isHomePage: false,
productType: productType,
scrollController: _scrollController),
),
),
],
),
),
),
);
}
}
The exception I'm getting is
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by gesture ═══════════════════════════════════════════
The getter 'iterator' was called on null.
Receiver: null
Tried calling: iterator

flutter PageView onPageChanged with setstate

i am working with PageView but if i swipe to change it will change the page But if i put onPageChanged to setState for me to get to current index it will not change the page.
here is my code
int _indicatorsPages = 0;
final PageController controller =
PageController(initialPage: 0);
change(int page) {
setState(() {
_indicatorsPages = page;
}); }
code from build
Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
leading: Row(
children: [
SizedBox(
width: 10,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SettingsFMC(),
),
);
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 1, blurRadius: 2,
offset: Offset(0, 3), // i change position of shadow
),
],
),
child: Center(
child: Icon(
FontAwesomeIcons.slidersH,
size: 20,
color: Colors.black,
)),
),
),
],
),
elevation: 0,
backgroundColor: Colors.transparent,
actions: [
GestureDetector(
onTap: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Actitvities(),
),
);
final doc = await firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.get();
if (doc.docs.isNotEmpty) {
firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.get()
.then((value) {
value.docs.forEach((doc) {
doc.reference.update({'seen': true});
});
});
}
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 1, blurRadius: 2,
offset: Offset(0, 3), // i change position of shadow
),
],
),
child: StreamBuilder(
stream: firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.where('seen', isEqualTo: false)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
));
}
if (snapshot.data.docs.isEmpty) {
return Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
));
}
return Badge(
animationType: BadgeAnimationType.scale,
badgeContent: Text('${snapshot.data.docs.length}'),
position: BadgePosition.topStart(),
showBadge: true,
child: Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
)),
);
}),
),
),
SizedBox(
width: 10,
),
],
),
extendBodyBehindAppBar: true,
body: userProfileLoading
? Center(
child: CircularProgressIndicator(),
)
: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height / 1.6,
child: StreamBuilder(
stream: firestore
.collection('Image')
.doc(widget.viewId)
.collection('Photos')
.orderBy('timestap', descending: false)
.snapshots(),
builder: (context, AsyncSnapshot snapshot) {
int idx = 0;
List<Widget> list = [];
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (!snapshot.hasData) {
return Center(
child: Text("No image Found, Add images"),
);
} else {
if (snapshot.hasError) {
return Center(child: Text("fetch error"));
} else {
for (int i = 0;
i < snapshot.data.docs.length;
i++) {
// print('the lent of the document is $idx');
list.add(
FullScreenWidget(
child: Hero(
tag: "customTag",
child: Image.network(
snapshot.data.docs[idx]
.data()['picture'],
fit: BoxFit.cover,
),
),
),
);
idx++;
}
return Stack(
children: [
PageView(
key: _key,
scrollDirection: Axis.horizontal,
controller: controller,
onPageChanged: change,
// onImageChange: (pre, current) {
// print('this current : $current');
// setState(() {
// indicatorsPages = current;
// });
// },
// boxFit: BoxFit.cover,
// autoplay: false,
// animationCurve: Curves.fastOutSlowIn,
// animationDuration:
// Duration(milliseconds: 1000),
// dotIncreasedColor: Colors.orange,
// dotBgColor: Colors.transparent,
// dotPosition: DotPosition.bottomCenter,
// dotVerticalPadding:
// MediaQuery.of(context).size.height / 15,
//showIndicator: false,
// indicatorBgPadding: 7.0,
children: list,
),
Positioned(
right:
MediaQuery.of(context).size.width / 2,
bottom: 75,
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: Colors.white),
child: indicat.DotsIndicator(
dotsCount: list.length,
position: _indicatorsPages.toDouble(),
decorator: DotsDecorator(
color:
Colors.grey, // Inactive color
activeColor: Colors.black,
),
)),
)
],
);
}
}
}),
),
You are wrong. When you use pageView, it will call onPageChnaged function after page changed. If you want to change page programmatically, you should use pageView.animateToPage() function.
import 'package:flutter/material.dart';
class OnBoarding extends StatefulWidget {
#override
_OnBoardingState createState() => _OnBoardingState();
}
class _OnBoardingState extends State<OnBoarding> {
PageController controller;
int currentIndex = 0;
#override
void initState() {
controller = PageController();
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent[200],
body: Stack(
children: [
PageView(
onPageChanged: onchahged,
controller: controller,
children: [
Container(
child: Image.asset('assets/fierceninja.png'),
),
Container(
child: Image.asset('assets/ninja.png'),
),
Container(
child: Image.asset('assets/ninjahead.jpg'),
),
],
),
],
),
);
}
onchahged(int index) {
setState(() {
currentIndex = index;
});
}
}
Here's a complete example.

Flutter close a dialog and reload page with filtered list of the condition selected

import 'package:flutter_event_app/constant/color.dart';
import 'package:flutter_event_app/network/models/categories.dart';
import 'package:flutter_event_app/network/models/event_model.dart';
import 'package:flutter_event_app/network/models/time.dart';
import 'package:flutter_event_app/network/services/event_api.dart';
import 'package:flutter_event_app/pages/event_detail_page.dart';
import 'package:flutter_event_app/pages/search/home_search.dart';
import 'package:flutter_event_app/widgets/event_card.dart';
import 'package:flutter_event_app/widgets/no_events.dart';
import 'package:flutter_event_app/widgets/onload.dart';
class SelectedCategory extends StatefulWidget {
// SelectedCategory(Categories categories);
final Categories categories;
final Time time;
SelectedCategory(this.categories, [this.time]);
#override
_SelectedCategoryState createState() => _SelectedCategoryState();
}
class _SelectedCategoryState extends State<SelectedCategory> {
Categories categories;
Time timing;
String timeselect;
// Event event;
void viewEventDetail(Events event) {
Navigator.of(context).push(
PageRouteBuilder(
opaque: false,
barrierDismissible: true,
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, animation, __) {
return FadeTransition(
opacity: animation,
child: EventDetailPage(event),
);
},
),
);
}
bool isLoading = false;
List<Events> upcomingEvents;
List categorizedupcomingEvents = [];
List categorizedPaidupcomingEvents = [];
List categorizedFreeupcomingEvents = [];
#override
void initState() {
_fetchData();
categories = widget.categories;
timing = widget.time;
// print(timing.id);
super.initState();
}
Future _fetchData() async {
setState(() => isLoading = true);
upcomingEvents = await getEventss();
categorizedupcomingEvents = upcomingEvents
.where((category) => category.category == categories.id)
.toList();
categorizedPaidupcomingEvents = categorizedupcomingEvents
.where((paid) => paid.is_paid == true)
.toList();
categorizedFreeupcomingEvents = categorizedupcomingEvents
.where((free) => free.is_paid == false)
.toList();
setState(() => isLoading = false);
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(
MediaQuery.of(context).size.height / 9.5,
),
child: AppBar(
title: Text(categories.categoryName),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.sort,
),
onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
showFilterByTimeDialog(context);
// )
// );
}),
IconButton(
icon: Icon(
Icons.more_vert,
),
onPressed: () {})
],
bottom: TabBar(
tabs: [
Text('All'),
Text('Paid'),
Text('Free'),
],
),
),
),
body: TabBarView(
children: <Widget>[
// All
isLoading
? OnloadingCards()
: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: categorizedupcomingEvents.isEmpty
? NoItems()
: ListView.builder(
itemCount: categorizedupcomingEvents.length,
shrinkWrap: true,
primary: false,
physics: BouncingScrollPhysics(),
// scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
final event =
categorizedupcomingEvents[index];
return EventCard(event,
onTap: () => viewEventDetail(event));
},
),
),
),
],
),
// Paid
isLoading
? OnloadingCards()
: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: categorizedPaidupcomingEvents.isEmpty
? NoItems()
: ListView.builder(
itemCount:
categorizedPaidupcomingEvents.length,
shrinkWrap: true,
primary: false,
physics: BouncingScrollPhysics(),
// scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
final event =
categorizedPaidupcomingEvents[index];
return EventCard(event,
onTap: () => viewEventDetail(event));
},
),
),
),
],
),
// Free
isLoading
? OnloadingCards()
: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: categorizedFreeupcomingEvents.isEmpty
? NoItems()
: ListView.builder(
itemCount:
categorizedFreeupcomingEvents.length,
shrinkWrap: true,
primary: false,
physics: BouncingScrollPhysics(),
// scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
final event =
categorizedFreeupcomingEvents[index];
return EventCard(event,
onTap: () => viewEventDetail(event));
},
),
),
),
],
),
],
),
));
}
void showFilterByTimeDialog(BuildContext context) {
Dialog fancyDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: SingleChildScrollView(
child: Container(
width: double.infinity,
height: MediaQuery.of(context).size.height * 0.5,
// alignment: Alignment.bottomCenter,
decoration: BoxDecoration(
// color: Colors.greenAccent,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
),
),
child: Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.05,
child: Text(
"Time",
style: TextStyle(
color: Colors.deepPurple,
fontSize: 20,
fontWeight: FontWeight.w600),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
// color: Colors.red,
width: double.infinity,
child: ListView.builder(
shrinkWrap: true,
primary: false,
physics: BouncingScrollPhysics(),
itemCount: times.length,
itemBuilder: (context, int index) {
Time time = times[index];
return RaisedButton(
onPressed: () {
debugPrint('I am Awesome');
},
textColor: Colors.red,
// color: Colors.blueAccent,
disabledColor: Colors.grey,
disabledTextColor: Colors.white,
highlightColor: Colors.orangeAccent,
child: Text(time.name),
);
}),
),
),
),
],
),
),
),
);
showDialog(
context: context, builder: (BuildContext context) => fancyDialog);
}
}
Within the same page I have a dialog box as shown below
On the method showFilterByTimeDialog where I select an item and have to go back to the same page below the dialogue .Am still learning flutter and my issue is I need help when I select an item from the dialogue box,i refresh the same page and display a new filtered lst from the current list displayed on that page with a condition of the item selected from the dialogue box.