Could not find the correct Provider<User> above this MainScreenPage Widget - flutter

I am getting the Error: Could not find the correct Provider above this MainScreenPage Widget. I cannot figure out what is wrong with my code since my MultiProvider is the parent of MaterialApp.
Things I tried which did not help:
Stopped debugging and started debugging.
Moved MultiProvider inside runApp, making MyApp its child.
I would very much appreciate it if anybody could help.
What shown on debug console
The relevant error-causing widget was
MainScreenPage lib/main.dart:22 (that is "widget = MainScreenPage();")
<main.dart>
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
User? firebaseUser = FirebaseAuth.instance.currentUser;
Widget widget;
if (firebaseUser != null) {
print(firebaseUser.email);
widget = MainScreenPage();
} else {
widget = LoginPage();
}
return MultiProvider(
providers: [
StreamProvider<User?>(
initialData: null,
create: (context) => FirebaseAuth.instance.authStateChanges(),
)
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'BookTracker',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: GoogleFonts.notoSansTextTheme(
Theme.of(context).textTheme,
),
),
home: widget,
),
);
}
}
<main_screen_page.dart>
class MainScreenPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
CollectionReference userCollectionReference =
FirebaseFirestore.instance.collection('users');
CollectionReference bookCollectionReference =
FirebaseFirestore.instance.collection('books');
List<Book> userBooksReadList = [];
// int booksRead = 0;
var authUser = Provider.of<User>(context);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white24,
elevation: 0,
toolbarHeight: 77,
centerTitle: false,
title: Row(
children: [
Text(
'A.Reader',
style: Theme.of(context).textTheme.headline6!.copyWith(
color: Colors.redAccent, fontWeight: FontWeight.bold),
),
],
),
actions: [
StreamBuilder<QuerySnapshot>(
stream: userCollectionReference.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final userListStream = snapshot.data!.docs.map((user) {
return MUser.fromDocument(user);
}).where((user) {
return (user.uid == authUser.uid);
}).toList();
MUser curUser = userListStream[0];
return Column(
children: [
InkWell(
child: SizedBox(
height: 40,
width: 40,
child: CircleAvatar(
radius: 60,
backgroundImage: NetworkImage(curUser.avatarUrl ??
'https://picsum.photos/id/1022/300'),
backgroundColor: Colors.white,
child: Text(''),
),
),
onTap: () {
showDialog(
context: context,
builder: (context) {
return createProfileDialog(
context, curUser, userBooksReadList);
},
);
},
),
Text(
curUser.displayName.toUpperCase(),
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
)
],
);
},
),
TextButton.icon(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
return Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
));
});
},
icon: Icon(Icons.logout),
label: Text(''),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookSearchPage(),
));
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.redAccent,
),
body: Column(
children: [
Container(
width: double.infinity,
margin: const EdgeInsets.only(top: 12, left: 12, bottom: 10),
child: RichText(
text: TextSpan(
style: Theme.of(context).textTheme.headline6,
children: [
TextSpan(text: '今、'),
TextSpan(
text: '読んでいるのは',
style: TextStyle(fontWeight: FontWeight.w600)),
TextSpan(text: '…'),
]),
),
),
SizedBox(
height: 10,
),
StreamBuilder<QuerySnapshot>(
stream: bookCollectionReference.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('問題が発生しました (T.T)');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Expanded(
flex: 1,
child: Center(
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.lime.shade300,
)));
}
if (snapshot.data!.docs.isEmpty) {
return Text('表示する書籍データがありません',
style: Theme.of(context).textTheme.headline4);
}
final userBookFilteredReadListStream =
snapshot.data!.docs.map((book) {
return Book.fromDocument(book);
}).where((book) {
return ((book.userId == authUser.uid)) &&
(book.finishedReading == null) &&
(book.startedReading != null);
}).toList();
userBooksReadList = snapshot.data!.docs.map((book) {
return Book.fromDocument(book);
}).where((book) {
return ((book.userId == authUser.uid)) &&
(book.finishedReading != null) &&
(book.startedReading != null);
}).toList();
return Expanded(
flex: 1,
child: (userBookFilteredReadListStream.length > 0)
? ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: userBookFilteredReadListStream.length,
itemBuilder: (context, index) {
Book book = userBookFilteredReadListStream[index];
return InkWell(
child: ReadingListCard(
buttonText: '読書中',
image: book.photoUrl!,
title: book.title,
author: book.author!,
rating: (book.rating) != null ? book.rating : 0,
),
onTap: () {
showDialog(
context: context,
builder: (context) {
return BookDetailDialog(
book: book,
);
},
);
},
);
},
)
: Text('読書中の本はありません (・o・)',
style: Theme.of(context).textTheme.headline6));
},
),
Container(
width: double.infinity,
margin: EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
text: TextSpan(children: [
TextSpan(
text: '読みたい本リスト',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
color: kBlackColor),
),
]),
),
],
),
),
SizedBox(
height: 8,
),
StreamBuilder<QuerySnapshot>(
stream: bookCollectionReference.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('問題が発生しました (T.T)');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Expanded(
flex: 1,
child: Center(
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.lime.shade300,
)));
}
if (snapshot.data!.docs.isEmpty) {
return Center(
child: Text('表示する書籍データがありません',
style: Theme.of(context).textTheme.headline4),
);
}
final readingListListBook = snapshot.data!.docs.map((book) {
return Book.fromDocument(book);
// ログイン中ユーザのuidでbookをフィルタリングする
}).where((book) {
return ((book.userId == authUser.uid)) &&
(book.startedReading == null) &&
(book.finishedReading == null);
}).toList();
return Expanded(
flex: 1,
child: (readingListListBook.length > 0)
? ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: readingListListBook.length,
itemBuilder: (context, index) {
Book book = readingListListBook[index];
return InkWell(
child: ReadingListCard(
buttonText: '未読',
rating: (book.rating) != null ? book.rating : 0,
image: book.photoUrl!,
title: book.title,
author: book.author!,
isBookRead: false,
),
onTap: () {
showDialog(
context: context,
builder: (context) {
return BookDetailDialog(
book: book,
);
},
);
},
);
},
)
: Text('表示する書籍データがありません ^_^;',
style: Theme.of(context).textTheme.headline6));
},
),
],
),
);
}
}

"var authUser = Provider.of<User>(context);" could you add a question mark to this syntax? It should look like this: "var authUser = Provider.of<User?>(context);"

Related

flutter putting data from api in expansion tile

Hew guys , i got a small question .
im making a drawer that should have a titles and a neste titles so i use an expansion tile.
so the titles are displayed but when i press the arrow to open the nested titles it gives me an error.
i used future builder in the nested titles i think this is the problem the error gives me this
The following TypeErrorImpl was thrown building FutureBuilder<List<dynamic>>(dirty, state: _FutureBuilderState<List<dynamic>>#aeb31):
Unexpected null value.
this is my drawer
Drawer Image
this is my drawer code
import 'package:MyCima/Screens/drawer_title_page.dart';
import 'package:MyCima/models/drawer_shows_data_model.dart';
import 'package:MyCima/services/services.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants.dart';
class FilmsDrawer extends StatefulWidget {
const FilmsDrawer({Key? key}) : super(key: key);
#override
_FilmsDrawerState createState() => _FilmsDrawerState();
}
class _FilmsDrawerState extends State<FilmsDrawer> {
final ServicesClass _services = ServicesClass();
late DrawerShowsDataModel _showsModelClass;
late Future drawerListData;
List nestedListNames = [];
#override
void initState() {
drawerListData = getDrawerList();
super.initState();
}
Future<List> getDrawerList() async {
return await _services.getFilms('menus');
}
#override
Widget build(BuildContext context) {
return Drawer(
elevation: 150,
semanticLabel: 'More Shows',
backgroundColor: PRIMARY,
child: Padding(
padding: const EdgeInsets.only(top: 24),
child: FutureBuilder(
future: drawerListData,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return const Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
return Column(
children: [
Expanded(
flex: 5,
child: Column(
children: [
Expanded(
flex: 9,
child: Text(
'MyCima',
style: GoogleFonts.bevan(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const Expanded(
flex: 1,
child: Divider(
color: Colors.white,
indent: 64,
endIndent: 64,
),
),
],
),
),
Expanded(
flex: 95,
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
_showsModelClass = DrawerShowsDataModel.fromJson(
snapshot.data[index]);
if (_showsModelClass.listChildren.length > 0) {
return ExpansionTile(
title: Text(
_showsModelClass.name,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
children: [
getNestedTitles(index),
],
);
} else {
return Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.all(8),
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DrawerTitlePage()));
},
child: Text(
'${_showsModelClass.name}',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
);
}
}),
),
],
);
case ConnectionState.none:
return const Center(child: Text('No Connection'));
}
},
),
),
);
}
getNestedTitles(int index){
return FutureBuilder(
future: getDrawerList(),
builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
return ListView.builder(
itemCount: snapshot.data![index]['children'].length,
itemBuilder: (BuildContext context, int index) {
_showsModelClass = DrawerShowsDataModel.fromNestedJson(snapshot.data![index]['children'][index]);
return TextButton(
onPressed: () {},
child: Text(
'${_showsModelClass.name}',
),
);
},
);
},
);
}
}
i found the answer
we need to make a list of widgets and add widgets on it then use it in the expansion
List<Widget> list = [];
List<Widget> getNestedTitles(int index) {
List<Widget> list = [];
drawerListData.then((value) {
for (var x in value[index]['children']) {
list.add(Padding(
padding: const EdgeInsets.all(8.0),
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DrawerTitlePage()));
},
child: Text('${x['name']}',
style: const TextStyle(
color: Colors.white,
),),
),
));
}
});
return list;
}

Exception caught by rendering library A RenderFlex overflowed by 98349 pixels on the right. The relevant error-causing widget was AppBar

[hello, i'm doing this site and impractical what happens, everything goes except the app bar (from another error that is index out of range index is 0) this site is connected to firebase, the problem i think is there just that i don't know how solve it mainly because I have looked a lot of times that the collections on firebase had the right names but still does not go does anyone have a solution?]
CollectionReference userCollectionReference =
FirebaseFirestore.instance.collection('users');
CollectionReference bookCollectionReference =
FirebaseFirestore.instance.collection('books');
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white24,
elevation: 0.0,
toolbarHeight: 77,
centerTitle: false,
title: Row(
children: [
Text(
'A.Reader',
style: Theme.of(context).textTheme.headline6.copyWith(
color: Colors.redAccent, fontWeight: FontWeight.bold),
),
],
),
actions: [
StreamBuilder<QuerySnapshot>(
stream: userCollectionReference.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final userListStream = snapshot.data.docs.map((user) {
return MUser.fromDocument(user);
}).where((user) {
return (user.uid == FirebaseAuth.instance.currentUser.uid);
}).toList(); //[user]
MUser curUser = userListStream[0];
print(userListStream);
return Column(
children: [
SizedBox(
height: 40,
width: 40,
child: InkWell(
child: CircleAvatar(
radius: 60,
backgroundImage: NetworkImage(
/* curUser.avatarUrl != null
? curUser.avatarUrl
: */
'https://i.pravatar.cc/300'),
backgroundColor: Colors.white,
child: Text(''),
),
onTap: () {
showDialog(
context: context,
builder: (context) {
// return createProfileMobile(context, userListStream,
// FirebaseAuth.instance.currentUser, null);
return createProfileDialog(context, curUser);
},
);
},
),
),
Text(
curUser.displayName.toUpperCase(),
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
)
],
);
},
),
TextButton.icon(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
return Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
));
});
},
icon: Icon(Icons.logout),
label: Text(''))
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookSearchPage(),
));
},
child: Icon(Icons.add),
backgroundColor: Colors.redAccent,
),
//error:
packages/flutter/src/widgets/async.dart 124:48 build
...
Exception caught by rendering library
A RenderFlex overflowed by 98349 pixels on the right.
The relevant error-causing widget was
AppBar
lib\screens\main_screen.dart:26
I think You Should write wrong code formatting try it out your code like below:
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white24,
elevation: 0.0,
toolbarHeight: 77,
centerTitle: false,
title: Text(
'A.Reader',
style: Theme.of(context).textTheme.headline6.copyWith(
color: Colors.redAccent, fontWeight: FontWeight.bold),
),
),
body:StreamBuilder<QuerySnapshot>(
stream: userCollectionReference.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final userListStream = snapshot.data.docs.map((user) {
return MUser.fromDocument(user);
}).where((user) {
return (user.uid == FirebaseAuth.instance.currentUser.uid);
}).toList(); //[user]
MUser curUser = userListStream[0];
print(userListStream);
return Column(
children: [
SizedBox(
height: 40,
width: 40,
child: InkWell(
child: CircleAvatar(
radius: 60,
backgroundImage: NetworkImage(
/* curUser.avatarUrl != null
? curUser.avatarUrl
: */
'https://i.pravatar.cc/300'),
backgroundColor: Colors.white,
child: Text(''),
),
onTap: () {
showDialog(
context: context,
builder: (context) {
// return createProfileMobile(context, userListStream,
// FirebaseAuth.instance.currentUser, null);
return createProfileDialog(context, curUser);
},
);
},
),
),
Text(
curUser.displayName.toUpperCase(),
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
)
],
);
},
),
TextButton(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
return Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
));
});
},
icon: Icon(Icons.logout),
label: Text(''))
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookSearchPage(),
));
},
child: Icon(Icons.add),
backgroundColor: Colors.redAccent,
));
remove your StreamBuilder inside action[] of appbar and add it to the body of scaffold

How to access the function inside a future builder from out side Parent widget or another future builder

i have a future builder which populate a list view ,inside there is a function total() which calculate ,pick the price of each item sum it and assign it to the subtotal variable . on the bottom i am showing the total price if i assiggn subtotal variable then it will return 0 for the first time because my function is in future builder ,i mean the function is executed after the value is assign.so i used another future builder for showing the total amount but i cannot access the total function as it is inside the future builder and it cannot be initialzed outside in the class because it has some data that won't be recognized outside.
so the problem is how can i access total function below ,i thought of global key but i don't know how to use it.
import 'package:flutter/material.dart';
import 'package:restaurant_ui_kit/models/user.dart';
import 'package:restaurant_ui_kit/screens/checkout.dart';
import 'package:restaurant_ui_kit/util/database_helper.dart';
class CartScreen extends StatefulWidget {
#override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen>
with AutomaticKeepAliveClientMixin<CartScreen> {
var db = new DatabaseHelper();
int _subTotal = 0;
List _users = [];
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Padding(
padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: FutureBuilder<List>(
future: db.getAllUsers(),
initialData: List(),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
final item = snapshot.data[position];
total(){
for (int i = 0; i < snapshot.data.length; i++) {
if (i == 0){
_subTotal =0;
}
_subTotal = _subTotal +
int.parse(
User.fromMap(snapshot.data[position]).price);
}
return _subTotal;
}
total();
// print('toatl is $_subTotal');
// get your item data here ...
return Dismissible(
key: UniqueKey(),
child: new Card(
color: Colors.white,
elevation: 2.0,
child: new ListTile(
leading: new CircleAvatar(
child: Text(
"${User.fromMap(snapshot.data[position]).name.substring(0, 1)}"),
),
title: new Text(
"User: ${User.fromMap(snapshot.data[position]).price}"),
subtitle: new Text(
"Id: ${User.fromMap(snapshot.data[position]).id}"),
onTap: () => debugPrint(
"${User.fromMap(snapshot.data[position]).id}"),
),
),
background: slideLeftBackground(),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
final bool res = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
"Are you sure you want to delete ${User.fromMap(snapshot.data[position]).name}?"),
actions: <Widget>[
FlatButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
// TODO: Delete the item from DB etc..
setState(() {
// total();
// print(position);
print('toatl is $_subTotal');
if (position == 0) {
//print('index 0 dai');
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
_subTotal = 0;
// print('toatl is 0 $_subTotal');
//snapshot.data.removeAt(position);
} else {
snapshot.data
.removeAt(--position);
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
total();
// print('toatl sewa $_subTotal');
}
//print("removed");
// print('mSubTotal $mSubTotal');
});
Navigator.of(context).pop();
},
),
],
);
});
return res;
}
},
);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
),
floatingActionButton: FloatingActionButton(
tooltip: "Checkout",
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Checkout();
},
),
);
},
child: Icon(
Icons.arrow_forward,
),
heroTag: Object(),
),
bottomSheet: Card(
elevation: 4.0,
child: Container(
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(10,5,5,5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Total",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w400,
),
),
FutureBuilder(
**future: total(),** the problem is here it cannot be accessed
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
return Text(
snapshot.data.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
);
}
return Container();
}
),
Text(
"Delivery charges included",
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
),
),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(5,5,10,5),
width: 150.0,
height: 50.0,
child: FlatButton(
color: Theme.of(context).accentColor,
child: Text(
"Place Order".toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: (){},
),
),
],
),
],
),
height: 70,
),
),
);
}
#override
bool get wantKeepAlive => true;
}
Well first off you can take out your total function and just pass in the data argument once it becomes available in the futurebuilder(like total(data){...}).
Now if you need the data that you got from db.getAllUsers(), you could also create a function like getAllUsers, where you would assign the gotten value to a class variable to be used later. Finally, unless the function total is asynchronous, it does not make sense to have a future builder for it. You can probably get away with calling setState once the total value is available.
Try this
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Padding(
padding: EdgeInsets.fromLTRB(10.0, 0, 10.0, 0),
child: FutureBuilder<List>(
future: db.getAllUsers(),
initialData: List(),
builder: (context, snapshot) {
total() {
num subTotal = 0;
for (int i = 0; i < snapshot.data.length; i++) {
subTotal += int.parse(User.fromMap(snapshot.data[i]).price);
}
setState(() {
_subTotal=subTotal;
});
}
if (snapshot.hasData) {
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, position) {
final item = snapshot.data[position];
total();
// print('toatl is $_subTotal');
// get your item data here ...
return Dismissible(
key: UniqueKey(),
child: new Card(
color: Colors.white,
elevation: 2.0,
child: new ListTile(
leading: new CircleAvatar(
child: Text(
"${User.fromMap(snapshot.data[position]).name.substring(0, 1)}"),
),
title: new Text(
"User: ${User.fromMap(snapshot.data[position]).price}"),
subtitle: new Text(
"Id: ${User.fromMap(snapshot.data[position]).id}"),
onTap: () => debugPrint(
"${User.fromMap(snapshot.data[position]).id}"),
),
),
background: slideLeftBackground(),
confirmDismiss: (direction) async {
if (direction == DismissDirection.endToStart) {
final bool res = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
"Are you sure you want to delete ${User.fromMap(snapshot.data[position]).name}?"),
actions: <Widget>[
FlatButton(
child: Text(
"Cancel",
style: TextStyle(color: Colors.black),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text(
"Delete",
style: TextStyle(color: Colors.red),
),
onPressed: () {
// TODO: Delete the item from DB etc..
setState(() {
// total();
// print(position);
print('toatl is $_subTotal');
if (position == 0) {
//print('index 0 dai');
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
_subTotal = 0;
// print('toatl is 0 $_subTotal');
//snapshot.data.removeAt(position);
} else {
snapshot.data.removeAt(--position);
db.deleteUser(User.fromMap(
snapshot.data[position])
.id);
total();
// print('toatl sewa $_subTotal');
}
//print("removed");
// print('mSubTotal $mSubTotal');
});
Navigator.of(context).pop();
},
),
],
);
});
return res;
}
return null;
},
);
},
);
}
return Center(child: CircularProgressIndicator());
},
),
),
floatingActionButton: FloatingActionButton(
tooltip: "Checkout",
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return Checkout();
},
),
);
},
child: Icon(
Icons.arrow_forward,
),
heroTag: Object(),
),
bottomSheet: Card(
elevation: 4.0,
child: Container(
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: <Widget>[
SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Total",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w400,
),
),
// changes
Text(
_subTotal.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
Text(
"Delivery charges included",
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
),
),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(5, 5, 10, 5),
width: 150.0,
height: 50.0,
child: FlatButton(
color: Theme.of(context).accentColor,
child: Text(
"Place Order".toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: () {},
),
),
],
),
],
),
height: 70,
),
),
);
}

Navigator operation requested with a context that does not include a Navigator - Flutter

i have a problem with navigator in my flutter file.
The problem is in my GestureDetector in _listItem, after tap on object, in my debug console throw me:
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
I don't have idea why this not work for me, can abybody help me?
below is my code:
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home:Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(100.0),
child: AppBar(
iconTheme: IconThemeData(color: Color.fromRGBO(9, 133, 46, 100)),
backgroundColor: Colors.white,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.shopping_cart,
color: Color.fromRGBO(9, 133, 46, 100),
),
onPressed: (){
print('klikniete');
},
),
],
),
),
body: Builder(
builder: (context) => Container(
child: FutureBuilder(
future: fetchOrders(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (_ordersForDisplay.length == null) {
return Container(
child: Center(child: Text("Ładowanie...")),
);
} else {
return ListView.builder(
itemCount: _ordersForDisplay.length + 1,
itemBuilder: (BuildContext context, int index) {
return index == 0 ? _searchBar() : _listItem(index - 1);
},
);
}
},
),
),
),
)
);
}
_listItem(index) {
return GestureDetector(
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => DetailPage(item: _ordersForDisplay[index])),
),
child: Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
_ordersForDisplay[index].firstName,
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
Text(
_ordersForDisplay[index].lastName,
style: TextStyle(
color: Colors.grey.shade600
),
),
],
),
),
),
);
}
}
class DetailPage extends StatelessWidget {
final Order item;
const DetailPage({this.item});
#override
Widget build(BuildContext context) {
return Center(
child: Text('${item.firstName} - ${item.lastName}')
);
}
}
Try changing your methods args as.
_listItem(index, context) { //Changes here
....
}
And pass the context where you called it.
return index == 0 ? _searchBar() : _listItem(index - 1,context);

check firestore has document or not using Future Builder

Full code
class yourBookings extends StatefulWidget {
#override
_yourBookingsState createState() => _yourBookingsState();
}
class _yourBookingsState extends State<yourBookings> {
StateModel appState;
bool _loadingVisible = false;
#override
Widget build(BuildContext context) {
appState = StateWidget.of(context).state;
final number = appState?.user?.number ?? '';
Future getPosts() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore
.collection("confirmed_c_rides2")
.document(number)
.collection("1")
.getDocuments();
return qn.documents;
}
return Scaffold(
appBar: AppBar(
title: Text("Your Bookings :"),
),
body: Container(
child: FutureBuilder(
future: getPosts(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("Loading ..."),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
Widget image_carousel = new Container(
height: 200.0,
child: new Carousel(
//borderRadius: BorderRadius.all(Radius.circular(2.0)),
boxFit: BoxFit.fitHeight,
images: [
Image.network(
"${snapshot.data[index].data["driverImage"]}"),
Image.network(
"${snapshot.data[index].data["carImage"]}")
],
autoplay: true,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 1000),
dotSize: 4.0,
indicatorBgPadding: 6.0,
dotBgColor: Colors.transparent,
),
);
return Card(
child: ListTile(
title: Column(
children: <Widget>[
SizedBox(height: 10),
Text(
"Status: ${snapshot.data[index].data["status"]}",
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
image_carousel,
Text(
"Name: ${snapshot.data[index].data["driverName"]}"),
SizedBox(height: 10),
Text(
"Gender: ${snapshot.data[index].data["gender"]}"),
SizedBox(height: 10),
Text(
"Experience: ${snapshot.data[index].data["experience"]}"),
SizedBox(height: 10),
Text(
"Number: ${snapshot.data[index].data["driverNumber"]}"),
SizedBox(height: 10),
Text(
"Time: ${snapshot.data[index].data["time"]}"),
SizedBox(height: 10),
Text(
"Scheduled on: ${snapshot.data[index].data["rideOn"]}"),
SizedBox(height: 10),
RaisedButton(
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => new issue()));
},
child: Text(
"Having issue",
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 10),
RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => rating1()));
},
child: Text("Rate driver"),
)
],
),
),
);
});
} else if (snapshot==null) {
return Center(
child: Text("not found..."),
);
}
return Center(
child: Text("not found 2..."),
);
}),
),
);
}
}
getPosts() refers to the firestore location for fetching data.
I want to check whether firestore contains number or not as a document using Future Builder.How can i do that?
number -> 1 contains further details.
If number does not exists then show data from firestore else show "not found...".How can i do that?
Future builder is used to stream firestore.