Navigator operation requested with a context that does not include a Navigator - Flutter - 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);

Related

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

when I click ElevatedButton(), Navigator.push() occurs Error: Navigator operation requested with a context that does not include a Navigator. But I make that ElevatedButton() in other dart file as widget, and I import It. It works well. What's the difference betweent make navigator button inside in code and import navigator button.
class GuideMainScreen extends StatelessWidget {
GuideMainScreen({super.key});
final _controller = PageController();
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
appBar: const AppbarSkip(),
body: Column(
children: [
SizedBox(
height: 570,
child: PageView(
controller: _controller,
children: const [
GuideHowScreen(),
GuideFocusScreen(),
GuideBreakScreen(),
],
),
),
Row(
children: [
const Padding(padding: EdgeInsets.only(left: 40)),
SmoothPageIndicator(
controller: _controller,
count: 3,
effect: const ExpandingDotsEffect(
activeDotColor: Color(0xFFE7626C),
dotColor: Color(
0xFF232B55,
),
),
),
const SizedBox()
],
),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 45,
),
),
const SizedBox(
width: 181,
height: 49,
// Error
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomeScreen(),
),
);
},
child: const Text(
'SKIP',
style: TextStyle(color: Colors.white),
),
);
// Works Well
child: SkipButton(),
),
],
),
),
);
}
}
this is SkiptButton() Widget which I write code in other dart file
import 'package:flutter/material.dart';
class SkipButton extends StatelessWidget {
const SkipButton({super.key});
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomeScreen(),
),
);
},
child: const Text(
'SKIP',
style: TextStyle(color: Colors.white),
),
);
}
}

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;
}

The class 'SimpleFoldingCell' doesn't have a default constructor

https://github.com/flutter-devs/flutter_folding_cell_demo/blob/master/lib/demo_screen.dart
I'm trying to follow the code in the link above.
But in the SimpleFoldingCell part, an error named 'The class 'SimpleFoldingCell' doesn't have a default constructor.' occurs.
Could
Is there a way to resolve this error in Dart?
class Notific extends StatefulWidget{
#override
_State createState() => _State();
}
class _State extends State<Notific>{
late List<TechnologyModel> _technologyList;
#override
void initState() {
super.initState();
_technologyList = [
TechnologyModel(title: "Application Development",),
TechnologyModel(title: "Research & Development",),
TechnologyModel(title: "Big Data & Analytics",),
TechnologyModel(title: "Support Services",),
TechnologyModel(title: "QA & Software Testing",),
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.pink[200],
title: Text("Folding Cell Demo",
style: TextStyle(color: Colors.white),),
),
body: Container(
child: ListView.builder(
itemCount: _technologyList.length,
itemBuilder: (context, index) {
return SimpleFoldingCell(
frontWidget: _buildFrontWidget(index),
innerTopWidget: _buildInnerWidget(index),
innerBottomWidget: _buildInnerBottomWidget(),
cellSize: Size(MediaQuery.of(context).size.width, 125),
padding: EdgeInsets.all(15),
animationDuration: Duration(milliseconds: 200),
borderRadius: 10,
onOpen: () => print('$index cell opened'),
onClose: () => print('$index cell closed'),
);
},
),
),
);
}
Widget _buildFrontWidget(int index) {
return Builder(
builder: (BuildContext context) {
return Container(
color: Colors.cyan[100],
alignment: Alignment.bottomCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Aeologic Technology",
style: TextStyle(
fontSize:20.0,
color: Colors.black,
),
),
SizedBox(height: 10,),
FlatButton(
onPressed: () {
final foldingCellState = context
.findAncestorStateOfType<SimpleFoldingCellState>();
foldingCellState?.toggleFold();
},
child: Text(
"OPEN",
),
textColor: Colors.white,
color: Colors.indigoAccent[100],
splashColor: Colors.white.withOpacity(0.5),
),
],
),
);
},
);
}
Widget _buildInnerBottomWidget() {
return Builder(
builder: (context) {
return Container(
color: Colors.blueGrey[50],
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(bottom: 10),
child: FlatButton(
onPressed: () {
final foldingCellState = context
.findAncestorStateOfType<SimpleFoldingCellState>();
foldingCellState?.toggleFold();
},
child: Text(
"Close",
),
textColor: Colors.white,
color: Colors.redAccent[100],
splashColor: Colors.white.withOpacity(0.5),
),
),
);
}
);
}
Widget _buildInnerWidget(int index) {
return Builder(
builder: (context) {
return Container(
color: Colors.pink[100],
padding: EdgeInsets.only(top: 10),
child: Align(
alignment: Alignment.center,
child: Text(
_technologyList[index].title,
style: TextStyle(
fontSize:20.0,
color: Colors.black,
),
),
),
);
},
);
}
}
class TechnologyModel {
String title;
TechnologyModel({
required this.title,
});
}
For some reason they've created only a named constructor.
return SimpleFoldingCell.create(
frontWidget: _buildFrontWidget(index),
innerWidget: _buildInnerWidget(index),
// innerTopWidget: _buildInnerWidget(index),
// innerBottomWidget: _buildInnerBottomWidget(),
cellSize: Size(MediaQuery.of(context).size.width, 125),
padding: EdgeInsets.all(15),
animationDuration: Duration(milliseconds: 200),
borderRadius: 10,
onOpen: () => print('$index cell opened'),
onClose: () => print('$index cell closed'),
);
It looks like the demo you're looking at is a bit outdated, since some of those properties don't exist anymore (see commented code).

how to get the id from statefull widget to stateless widget in flutter?

I need to get the id from quizCatId in the category() class to QuizTile() can someone tell me how to solve the issue...
my need is to call subcategory data from firestore which has an quizid and quizcatid and there I have my quizdata so I need to pass both the id to the quizdata to get data from the firestore
class Category extends StatefulWidget {
String quizCatId;
Category(this.quizCatId);
#override
_CategoryState createState() => _CategoryState();
}
class _CategoryState extends State<Category> {
Stream quizStream;
DatabaseService databaseService = new DatabaseService();
Widget quizList() {
return Container(
child: Column(
children: [
StreamBuilder(
stream: quizStream,
builder: (context, snapshot) {
return snapshot.data == null
? Container()
: ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
return QuizTile(
noOfQuestions: snapshot.data.documents.length,
imageUrl:
snapshot.data.documents[index].data['quizImgUrl'],
title:
snapshot.data.documents[index].data['quizTitle'],
desc: snapshot.data.documents[index].data['quizDesc'],
quizid: snapshot.data.documents[index].data["quizId"],
);
});
},
),
],
),
);
}
#override
void initState() {
databaseService.getCatData(widget.quizCatId).then((value) {
quizStream = value;
setState(() {});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: appBar(context),
brightness: Brightness.light,
elevation: 0.0,
backgroundColor: Colors.transparent,
//brightness: Brightness.li,
),
body: SingleChildScrollView(child: quizList()),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CreateCategoryQuiz()));
},
),
);
}
}
class QuizTile extends StatelessWidget {
final String imageUrl, title, quizid, desc, quizcatId;
final int noOfQuestions;
QuizTile({
#required this.title,
#required this.imageUrl,
#required this.desc,
#required this.quizid,
#required this.noOfQuestions,
#required this.quizcatId,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PlayQuiz(quizid, quizcatId)));
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 14),
height: 150,
margin: EdgeInsets.only(bottom: 8),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
children: [
Image.network(
imageUrl,
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
),
Container(
color: Colors.black26,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
title,
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w500),
),
SizedBox(
height: 4,
),
Text(
desc,
style: TextStyle(
fontSize: 13,
color: Colors.white,
fontWeight: FontWeight.w500),
)
],
),
),
)
],
),
),
),
);
}
}
Hey you have acces to statefulWidget properties form state class by windget property.
All you have to do is ad new parameter in QuizTile constructor and call them
QuizTile(
noOfQuestions: snapshot.data.documents.length,
imageUrl:
snapshot.data.documents[index].data['quizImgUrl'],
title:
snapshot.data.documents[index].data['quizTitle'],
desc: snapshot.data.documents[index].data['quizDesc'],
quizid: snapshot.data.documents[index].data["quizId"],
quizCatId: widget.quizCatId
);

Adding an Icon to a List using a button and actively updating UI using Provider state management

I want to add an Icon to a List following UI update using flutter Provider state Management.
I was successful to add an Icon using the floating button and confirm the result by printing the new List length. This ensures the addition of an Icon to a List but it does not update the UI for the new added Icon. Snippets are below
#override
_MedicalCosmeticsDetailsPageState createState() =>
_MedicalCosmeticsDetailsPageState();
}
class _MedicalCosmeticsDetailsPageState
extends State<MedicalCosmeticsDetailsPage> {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return ChangeNotifierProvider<GridIcons>(
create: (context) => GridIcons(),
child: SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(color: Colors.purple),
title: Text(
'xyz',
style: TextStyle(color: Colors.purple),
),
backgroundColor: Colors.transparent,
elevation: size.width * 0.05,
actions: [
Padding(
padding: EdgeInsets.only(right: size.width * 0.01),
child: IconButton(
icon: Icon(
Icons.search,
),
onPressed: () {},
),
),
],
),
body: GridViewPage(),
floatingActionButton: Consumer<GridIcons>(
builder: (context, myIcons, _) {
return FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
print(myIcons.iconList.length);
myIcons.addIcon();
},
);
},
),
),
),
);
}
}
```//floating button for adding an ICON
```class GridIcons with ChangeNotifier {
List<IconData> iconList = [
Icons.ac_unit,
Icons.search,
Icons.arrow_back,
Icons.hdr_on_sharp,
];
addIcon<IconData>() {
iconList.add(Icons.sentiment_dissatisfied);
notifyListeners();
}
getIconList<IconData>() {
return iconList;
}
}
```//Function for icon addition
class GridViewPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
List _iconList = GridIcons().getIconList();
return ChangeNotifierProvider<GridIcons>(
create: (context) => GridIcons(),
child: Consumer<GridIcons>(
builder: (context, myIcon, child) {
return GridView.builder(
itemCount: _iconList.length,
padding: EdgeInsets.all(8.0),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 250.0),
itemBuilder: (BuildContext context, int index) {
print('_buildGridViewBuilder $index');
return Card(
color: Colors.purple.shade300,
margin: EdgeInsets.all(8.0),
child: InkWell(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
_iconList[index],
size: 48.0,
color: Colors.purple.shade100,
),
Divider(),
Text(
'Index $index',
textAlign: TextAlign.center,
style: GoogleFonts.dmSans(
fontSize: 16,
color: Colors.white,
),
),
],
),
onTap: () {
print('Row: $index');
},
),
);
},
);
},
),
);
}
}
The icon doesn't appear in the UI although an icon is added to the Icon List.
You can copy paste run full code below
Step 1: In GridViewPage, you do not need ChangeNotifierProvider
Step 2: remove List _iconList = GridIcons().getIconList();
Step 3: use myIcon.iconList.length and myIcon.iconList[index]
code snippet
class GridViewPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
//List _iconList = GridIcons().getIconList();
return Consumer<GridIcons>(
builder: (context, myIcon, child) {
return GridView.builder(
itemCount: myIcon.iconList.length,
...
Icon(
myIcon.iconList[index],
size: 48.0,
working demo
full code
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
class MedicalCosmeticsDetailsPage extends StatefulWidget {
#override
_MedicalCosmeticsDetailsPageState createState() =>
_MedicalCosmeticsDetailsPageState();
}
class _MedicalCosmeticsDetailsPageState
extends State<MedicalCosmeticsDetailsPage> {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return ChangeNotifierProvider<GridIcons>(
create: (context) => GridIcons(),
child: SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(color: Colors.purple),
title: Text(
'xyz',
style: TextStyle(color: Colors.purple),
),
backgroundColor: Colors.transparent,
elevation: size.width * 0.05,
actions: [
Padding(
padding: EdgeInsets.only(right: size.width * 0.01),
child: IconButton(
icon: Icon(
Icons.search,
),
onPressed: () {},
),
),
],
),
body: GridViewPage(),
floatingActionButton: Consumer<GridIcons>(
builder: (context, myIcons, _) {
return FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
print(myIcons.iconList.length);
myIcons.addIcon();
},
);
},
),
),
),
);
}
}
class GridIcons with ChangeNotifier {
List<IconData> iconList = [
Icons.ac_unit,
Icons.search,
Icons.arrow_back,
Icons.hdr_on_sharp,
];
addIcon<IconData>() {
iconList.add(Icons.sentiment_dissatisfied);
notifyListeners();
}
getIconList<IconData>() {
return iconList;
}
}
class GridViewPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
//List _iconList = GridIcons().getIconList();
return Consumer<GridIcons>(
builder: (context, myIcon, child) {
return GridView.builder(
itemCount: myIcon.iconList.length,
padding: EdgeInsets.all(8.0),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 250.0),
itemBuilder: (BuildContext context, int index) {
print('_buildGridViewBuilder $index');
return Card(
color: Colors.purple.shade300,
margin: EdgeInsets.all(8.0),
child: InkWell(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
myIcon.iconList[index],
size: 48.0,
color: Colors.purple.shade100,
),
Divider(),
Text(
'Index $index',
textAlign: TextAlign.center,
style: GoogleFonts.dmSans(
fontSize: 16,
color: Colors.white,
),
),
],
),
onTap: () {
print('Row: $index');
},
),
);
},
);
},
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MedicalCosmeticsDetailsPage());
}
}