The argument type 'Future<>' can't be assigned to the parameter type '' - flutter

I am trying to build a GridView list. This all works when I create a simple list of 'players', but now I am trying to persist data using sqflite and I am getting an error:
Error: The argument type 'Future' can't be assigned to the parameter type 'int'
This is my list builder widget:
class PlayerList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<PlayerData>(
builder: (context, playerData, child) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemCount: playerData.playerCount,
itemBuilder: (BuildContext context, int index) {
final player = playerData.players[index];
return RawMaterialButton(
fillColor: Color(0x991c5597),
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.tealAccent,
radius: 30,
child: Icon(
Icons.star,
color: Color(0xFF16377a),
size: 30,
),
),
Text(player.name, style: smallTitleText),
],
),
),
onPressed: () {
playerData.makeActive(player.name);
playerData.printList();
Navigator.pushNamed(context, PlayScreen.id);
});
});
},
);
}
}
This is how I get the list count:
Future<int> get playerCount async {
final Database db = await getDBConnector();
final List<Map<String, dynamic>> maps = await db.query('players');
if (maps.length != null) {
return maps.length;
} else { return 0;}
}

Wrap your GridView with FutureBuilder
Something like this
return FutureBuilder(
future: playerData.playerCount,
builder : (context,snapshot){
if(!(snapshot.hasData)){
return Container();
}
else{
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemCount: snapshot.data,
itemBuilder: (BuildContext context, int index) {
final player = playerData.players[index];
return RawMaterialButton(
fillColor: Color(0x991c5597),
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.tealAccent,
radius: 30,
child: Icon(
Icons.star,
color: Color(0xFF16377a),
size: 30,
),
),
Text(player.name, style: smallTitleText),
],
),
),
onPressed: () {
playerData.makeActive(player.name);
playerData.printList();
Navigator.pushNamed(context, PlayScreen.id);
});
});
},
);
}
}
);

The error is appearing because playerCount isn't returning int its returning a Future. First, you have to change your class to a stateful widget and load your data as shown below
class PlayerList extends StatefulWidget {
#override
_PlayerListState createState() => _PlayerListState();
}
class _PlayerListState extends State<PlayerList> {
int count;
#override
void initState() {
super.initState();
loadPlayerCount();
}
#override
Widget build(BuildContext context) {
return Consumer<PlayerData>(
builder: (context, playerData, child) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemCount: count??0,
itemBuilder: (BuildContext context, int index) {
final player = playerData.players[index];
return RawMaterialButton(
fillColor: Color(0x991c5597),
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.tealAccent,
radius: 30,
child: Icon(
Icons.star,
color: Color(0xFF16377a),
size: 30,
),
),
Text(player.name, style: smallTitleText),
],
),
),
onPressed: () {
playerData.makeActive(player.name);
playerData.printList();
Navigator.pushNamed(context, PlayScreen.id);
});
});
},
);
}
void loadPlayerCount() async{
final Database db = await getDBConnector();
final List<Map<String, dynamic>> maps = await db.query('players');
if (maps.length != null) {
setState(() {
this.count = maps.length;
});
} else {
setState(() {
this.count = 0;
});
}
}
}

Related

My page overlaps when I switch between screens

https://www.veed.io/view/a97effbf-7aad-4c0a-8fd7-8fce2be4808e?sharingWidget=true&panel=share
I hate how when I slide between screens the layout overlaps to the next screen before rendering what's supposed to be there. How do I fix this?
This is the code for the page:
class StallPage extends StatefulWidget {
final Stall stall;
const StallPage({super.key, required this.stall});
#override
State<StallPage> createState() => _StallPageState();
}
class _StallPageState extends State<StallPage> {
var selected = 0;
final pageController = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xff392850), //kBackground,
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomAppBar(
Icons.arrow_back_ios_outlined,
Icons.search_outlined,
leftCallback: () => Navigator.of(context).pop(),
rightCallback: () => Navigator.of(context).pushNamed(searchRoute),
),
StallInfo(
stall: widget.stall,
), //
FoodList(
selected,
(int index) {
setState(() {
selected = index;
});
pageController.jumpToPage(index);
},
widget.stall,
),
Expanded(
child: FoodListView(
selected,
(int index) {
setState(() {
selected = index;
});
},
pageController,
widget.stall,
),
),
Container(
padding: EdgeInsets.symmetric(horizontal: 25),
height: 60,
child: SmoothPageIndicator(
controller: pageController,
count: widget.stall.menu.length,
effect: CustomizableEffect(
dotDecoration: DotDecoration(
width: 8,
height: 8,
color: Colors.grey.withOpacity(0.5),
borderRadius: BorderRadius.circular(8),
),
activeDotDecoration: DotDecoration(
width: 10,
height: 10,
color: kBackground,
borderRadius: BorderRadius.circular(10),
dotBorder: const DotBorder(
color: kPrimaryColor,
padding: 2,
width: 2,
),
),
),
onDotClicked: (index) => pageController.jumpToPage(index),
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: kPrimaryColor,
elevation: 2,
child: IconButton(
icon: Icon(Icons.shopping_cart_outlined),
color: Colors.black,
onPressed: () {
Navigator.of(context).pushNamed(cartRoute);
context.read<TotalPrice>().update();
},
),
),
);
}
}
FoodList: //I'm positive the problems somewhere here
class FoodList extends StatelessWidget {
final int selected;
final Function callback;
final Stall stall;
const FoodList(this.selected, this.callback, this.stall);
#override
Widget build(BuildContext context) {
final category = stall.menu.keys.toList();
return Container(
height: 100,
padding: const EdgeInsets.symmetric(vertical: 30),
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 25),
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => GestureDetector(
onTap: () => callback(index),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: selected == index ? kPrimaryColor : Colors.white,
),
child: Text(
category[index],
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
),
separatorBuilder: (_, index) => const SizedBox(width: 20),
itemCount: category.length,
),
);
}
}
FoodListView:
class FoodListView extends StatelessWidget {
final int selected;
final Function callback;
final PageController pageController;
final Stall stall;
const FoodListView(
this.selected,
this.callback,
this.pageController,
this.stall,
);
#override
Widget build(BuildContext context) {
final category = stall.menu.keys.toList();
return Container(
padding: EdgeInsets.symmetric(horizontal: 25),
child: PageView(
controller: pageController,
onPageChanged: (index) => callback(index),
children: category
.map((e) => ListView.separated(
padding: EdgeInsets.zero,
itemBuilder: (context, index) => GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DetailPage(
stall.menu[category[selected]]![index],
),
),
);
},
child:
FoodItem(stall.menu[category[selected]]![index])),
separatorBuilder: (_, index) => const SizedBox(height: 15),
itemCount: stall.menu[category[selected]]!.length,
))
.toList()),
);
}
}
Stall:
class Stall {
String name;
String label;
String logoUrl;
String desc;
num score;
Map<String, List<Food>> menu;
Stall(
this.name,
this.label,
this.logoUrl,
this.desc,
this.score,
this.menu,
);
}
No need to pass selected to FoodListView and also FoodListView will be like following
class FoodListView extends StatelessWidget {
final Function callback;
final PageController pageController;
final Stall stall;
const FoodListView(
this.callback,
this.pageController,
this.stall,
);
#override
Widget build(BuildContext context) {
final menuList = stall.menu.values.toList();
return Container(
padding: EdgeInsets.symmetric(horizontal: 25),
child: PageView.builder(
controller: pageController,
onPageChanged: (index) => callback(index),
itemCount: menuList.length,
itemBuilder: (context, menuIndex) {
final menu = menuList[menuIndex];
return ListView.separated(
padding: EdgeInsets.zero,
itemBuilder: (context, index) => GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DetailPage(
menu[index],
),
),
);
},
child: FoodItem(menu[index])),
separatorBuilder: (_, index) => const SizedBox(height: 15),
itemCount: menu.length,
);
},
));
}
}
Remove selected where you call FoodListView

Card stuck at it's previous postion after performing search. Trying to search constitutions using the titles from an API

Constitution Card stuck at its position after performing search instead of moving to the top first position in the gridview. The searched card is supposed to appear at the the index[0] of the gridview where "Test Constitution" when filtered after performing search .
Could post images because of low reputution from Stackoverflow
Before Search
After Search
This's the code.
class _HomePageState extends State<HomePage> {
final ConstitutionController constitutionController = Get.find();
String search = "";
#override
Widget build(BuildContext context) {
final double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xFF0B3C5D),
elevation: 0.0,
),
drawer: DrawerWidget(),
body: Stack(children: [
Container(
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
Text(),
),
// The Search bar
Container(
margin: const EdgeInsets.symmetric(vertical: 30),
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: CupertinoSearchTextField(
onChanged: ((value) {
setState(() {
search = value;
}
);
}),
autofocus: true,
itemColor: Colors.black,
itemSize: 20,
backgroundColor: const Color.fromARGB(255, 185, 204, 218),
placeholderStyle: const TextStyle(
color: Colors.black,
fontSize: 18,
),
),
),
const SizedBox(
height: 70,
),
Flexible(
child: Obx(() {
if (constitutionController.isLoading.value) {
return GridView.builder(
itemBuilder: (_, __) {
return Shimmer.fromColors(
baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!,
period: Duration(seconds: 2),
enabled: constitutionController.isLoading.value,
child: ShimmerGridCard());
},
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
);
} else {
return GridView.builder(
itemCount:
constitutionController.constitutionList.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemBuilder: (context, index) {
Constitution constitution =
constitutionController.constitutionList[index];
if (search.isEmpty) {
return InkWell(
onTap: (() {
Get.to(BranchPage(
constitutionId: constitution));
}),
child: ConstitutionCard(constitutionController
.constitutionList[index]));
}
if (constitution.title
.toLowerCase()
.contains(search)) {
return InkWell(
onTap: (() {
Get.to(BranchPage(
constitutionId: constitution));
}),
child: ConstitutionCard(constitutionController
.constitutionList[index]));
}
return null;
});
}
}),
),
],
),
),
),
]),
);
}
}

Grivdview search not working properly flutter

I have a gridview,i have implemented search,search is working fine,but the viewing of search item is not shows properly,
Before search
This how my gridview show after searching a item
Code
SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 6 / 5,
// crossAxisCount: 2,
crossAxisSpacing: 0,
mainAxisSpacing: 0),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
SubCategoryModel data = sub_category_model[index];
if (searchController.text.isEmpty) {
return GestureDetector(
child: Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 0,
child: Container(
width: 100,
height: 100.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: CachedNetworkImage(
fit: BoxFit.fill,
imageUrl: Urls.BASE_IMAGE_URL +
data.image.toString(),
placeholder: (context, url) => Center(
child: CircularProgressIndicator()),
errorWidget: (context, url, error) =>
Icon(Icons.error),
),
),
)),
Expanded(
flex: 0,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
child: Text(
data.name,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 13),
),
),
)
],
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OnlinecartSubitems(data.id.toString(),Category_Name),
),
);
},
);
} else if (data.name.contains(searchController.text) ||
data.name.toLowerCase().contains(searchController.text) ||
data.name.toUpperCase().contains(searchController.text)) {
return GestureDetector(
child: Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 0,
child: Container(
width: 100,
height: 100.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: CachedNetworkImage(
fit: BoxFit.fill,
imageUrl: Urls.BASE_IMAGE_URL +
data.image.toString(),
placeholder: (context, url) => Center(
child: CircularProgressIndicator()),
errorWidget: (context, url, error) =>
Icon(Icons.error),
),
),
)),
Expanded(
flex: 0,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
child: Text(
data.name,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 13),
),
),
)
],
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OnlinecartSubitems(data.id.toString(),Category_Name),
),
);
},
);
} else {
return Container();
}
},
childCount: sub_category_model.length,
),
)
Why not make a new list each time the search matches an item. Then, build a New GridView object based on the newly created list. Whenever your TextView is empty, you return the original list.
For Instance
//Create Search List
List<Object> searchList = [];
//Check if SearchTextView is empty or not with a ternary Operator
controller.text.isEmpty?
//Build your GridView based on the Original List
GridView.count(
...
itemCount: mainList.length,
...
) //Replace with you SliverGrid
//Build your GridView based on the Search List
: GridView.count(
...
itemCount: searchList.length
...
),//Replace with you SliverGrid
You can Replace my GridView with your SilverGrid widget.
The full Code (Spoiler alert: Very long):
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key key, #required this.title}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//Search TextField Controller
final _searchController = TextEditingController();
List<Fruit> mainList = [
Fruit(name: 'Apple', imageUrl: 'https://images.pexels.com/photos/102104/pexels-photo-102104.jpeg'),
Fruit(name: 'Banana', imageUrl: 'https://images.pexels.com/photos/5945848/pexels-photo-5945848.jpeg'),
Fruit(name: 'Pineapple', imageUrl: 'https://images.pexels.com/photos/1071878/pexels-photo-1071878.jpeg'),
Fruit(name: 'Mango', imageUrl: 'https://images.pexels.com/photos/918643/pexels-photo-918643.jpeg'),
];
List<Fruit> searchList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: 60.0,
child: TextFormField(
controller: _searchController,
onChanged: (text){
final String queryString = _searchController.text;
setState((){
if(queryString.isNotEmpty){
for(final fruit in mainList){
if(fruit.name.contains(queryString)){
searchList.add(fruit);
} else{
searchList.remove(fruit);
}
}
}else{
searchList.clear();
}
});
}
),
),
Expanded(
child: _searchController.text.isEmpty
? GridView.count(
crossAxisCount: 2,
children: mainList.map((fruit)=> CardWidget(fruit: fruit)).toList(),
)
:GridView.count(
crossAxisCount: 2,
children: searchList.map((searchedFruit)=>CardWidget(fruit: searchedFruit)).toList()
),
),
],
),
);
}
}
Create a Class to hold Fruit
class Fruit{
final String imageUrl;
final String name;
Fruit({this.imageUrl, this.name});
}
Create widget to be built for each fruit object found in the mainList
//Card Widget
class CardWidget extends StatefulWidget{
final Fruit fruit;
CardWidget({this.fruit});
#override
_CardWidgetState createState()=> _CardWidgetState();
}
class _CardWidgetState extends State<CardWidget>{
#override
Widget build(BuildContext context){
return Container(
width: 100.0,
height: 140.0,
child: Column(
children:[
Image(image: NetworkImage(widget.fruit.imageUrl)),
SizedBox(height: 10.0),
Text(widget.fruit.name),
]
)
);
}
}
Try it and let see
I have fixed the issue with help of Benedict and Farhan Syah thanks for the idea and some codes
Initialize variables
//Search controller for textfield
TextEditingController searchController = TextEditingController();
//For show list data first
List<SubCategoryModel> sub_category_model = [];
//for searchresult list
List<SubCategoryModel> _searchResult = [];
View
_searchResult.length != 0 ||searchController.text.isNotEmpty?SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 6 / 5,
// crossAxisCount: 2,
crossAxisSpacing: 0,
mainAxisSpacing: 0),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
SubCategoryModel data = _searchResult[index];
return GestureDetector(
child: Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 0,
child: Container(
width: 100,
height: 100.0,
child: ClipRRect(
borderRadius:
BorderRadius.circular(10.0),
child: CachedNetworkImage(
fit: BoxFit.fill,
imageUrl: Urls.BASE_IMAGE_URL +
data.image.toString(),
placeholder: (context, url) => Center(
child:
CircularProgressIndicator()),
errorWidget: (context, url, error) =>
Icon(Icons.error),
),
),
)),
Expanded(
flex: 0,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 10),
child: Text(
data.name,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 13),
),
),
)
],
),
),
onTap: () {
},
);
},
childCount: _searchResult.length,
),
):SliverGrid(//use same code above with **sub_category_model.length**)
Search widget
Widget _SearchText() {
return Container(
width: 360,
height: 65,
color: Colors.transparent,
child: new Padding(
padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
child: new Card(
elevation: 8,
child: TextField(
decoration: new InputDecoration(
filled: true,
hintStyle: TextStyle(fontSize: 11.5),
hintText: 'Search by Name',
suffixIcon: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
searchController.clear();
_searchResult.clear();
},
child: Icon(Icons.cancel_rounded,
color: Color.fromRGBO(34, 83, 148, 1))),
prefixIcon:
Icon(Icons.search, color: Color.fromRGBO(34, 83, 148, 1)),
border: InputBorder.none),
onChanged: onSearchTextChanged,
controller: searchController,
),
),
),
);
}
Onchanged function for searching through list
onSearchTextChanged(String text) async {
//clear search data before typing
_searchResult.clear();
if (text.isEmpty) {
setState(() {});
return;
}
//use searchcontroller text and loop through list of api data and add the result to _searchResult
sub_category_model.forEach((searchValue) {
if (searchValue.name.toLowerCase().contains(text))
_searchResult.add(searchValue);
});
setState(() {});
}
You are returning Container() when the search condition doesn't match. Container itself will take a place of a widget, hence, it will be an item of the grids.
To test this, you can try putting something inside the container, such as:
Container(
child: Text('This grid is not empty)
)
The problem with this, is if you have 12 items in the data, no matter your search result, it will still build 12 items (including the empty container)
To solve this, you need a better way to filter the data, such as using a list to filter, and then passing the list data to the grid builder.
The concept is like this:
Original list : 10 items
Newlist based on the search: 5 items
The grid builder will build the items based on the list provided.

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.

Flutter Firebase: not able update Database

I want to update my Collection with an NumberPicker in a Alert Dialog. I do not get any errors in code or from the emulator. When i press the button to update the code the terminal do not give any errors. Everything looks fine but for some reason i do not work. When you need more Information just leave a comment with what you excactly need. :)
import 'package:flutter/material.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:testapp/services/Services.dart';
import 'models/Goals.dart';
class Statistics extends StatefulWidget {
#override
_StatisticsState createState() => _StatisticsState();
}
class _StatisticsState extends State<Statistics> {
int _currentFirstValue = 1;
int totalFirst;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 260,
child: StreamBuilder(
stream: FirestoreService().getGoals(),
builder: (context, AsyncSnapshot<List<Goal>> snapshot) {
if (snapshot.hasError || !snapshot.hasData) {
return Center(child: CircularProgressIndicator(
backgroundColor: Color(0XFF1954A1),
));
}
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
// ignore: missing_return
Goal goal = snapshot.data[index];
return Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
height: 230,
width: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey[300],
offset: const Offset(0.5, 1),
blurRadius: 4.0,
spreadRadius: 0.1,
),
]),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text('WeekGoals', style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),),
SizedBox(width: 100),
SizedBox(
height: 20,
width: 87,
child: FlatButton(
child: Text('edit', style: TextStyle(
fontSize: 17,
color: Colors.yellow[700]
),),
onPressed: () {
return showDialog(
context: context,
barrierDismissible: true,
builder: (context) => AlertDialog(
content: Column(
children: <Widget>[
Text('weekly goals'),
NumberPicker.integer(
initialValue: _currentFirstValue,
minValue: 1,
maxValue: 100,
onChanged: (newGoal) => setState(() => {
_currentFirstValue = newGoal,
totalFirst = _currentFirstValue,
})
),
Row(
children: <Widget>[
RaisedButton(
child: Text('edit goals'),
onPressed: () async {
Goal goal = Goal(
weekActivityGoal: totalFirst,
);
await FirestoreService().updateGoal(goal);
Navigator.pop(context, false);
},
),
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.pop(context, false);
},
)
],
)
],
),
)
);
},
),
)
],
),
SizedBox(height: 10),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 17.5),
child: CircularPercentIndicator(
header: Text('activitys', style: TextStyle(
fontSize: 17,
),),
radius: 130,
progressColor: Colors.red,
lineWidth: 8,
backgroundColor: Colors.grey[200],
percent: goal.weekActivity*100/goal.weekActivityGoal,
center: Text('${goal.weekActivity}/${goal.weekActivityGoal}'),
),
),
],
),
],
),
),
],
);
});
}),
),
);
}
}
Here this has been helping a lot of people try i out might help you too.
StreamBuilder(
stream: Firestore.instance.collection('Hearings').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Select lot');
case ConnectionState.waiting:
return Text('Awaiting bids...');
case ConnectionState.active:
{
print('active');
return Text('${snapshot.data}');
}
case ConnectionState.done:
{
print('Done');
return _buildList(context, snapshot.data);
}
}
return null;
}),
));
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => Firestore.instance.runTransaction((transaction) async {
final freshSnapshot = await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction
.update(record.reference, {'votes': fresh.votes + 1});
}),
),
),
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
This is where the link this info came from.