I am trying to move to another screen from my homepage using the floating action button but unfortunately, the floating action button is not working. On tapping the button the next screen does not appear the console is showing context issues but I have been unable to go around it.
import 'package:flutter/material.dart';
import 'package:kitchen/Screen/kitchenscreen.dart';
import 'package:kitchen/Screen/FoodScreen.dart';
void main ()
{
runApp(myapp());
}
class myapp extends StatelessWidget
{
@override
Widget build(BuildContext context)
{
return MaterialApp(
home:Scaffold
(
backgroundColor:Colors.white60,
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('Teach'),
actions: [
IconButton(onPressed:(){},
icon: const Icon(Icons.favorite),)
] ,
),
body:const Center(
child: Text('Add Content here'),
),
floatingActionButton: FloatingActionButton(
onPressed: (){Navigator.push(context,
MaterialPageRoute(builder: (context)=>FoodScreen()),);},
backgroundColor:Colors.green,
child:const Icon(Icons.add),
),
)
);
}
}
import 'package:flutter/material.dart';
class FoodScreen extends StatelessWidget{
const FoodScreen({Key ? key}) :super(key:key);
Widget build(BuildContext context)
{
return const Scaffold(
body:Center(child:Text('hello')));
}
}
I was trying to get a screen after tapping the Floating action button but unfortunately on tapping the screen doesn’t appear.
2
Answers
You can use a
Builder
widget to provide a validcontext
:Because the
context
you pass toNavigator.push
is wrong. It is the context ofmyapp
, which isn’t stay inside yourScaffold
widget.If you want to use
Navigator
, then you must pass thecontext
that stay inside Scaffold. TryBuilder
to have thecontext
stay insideScaffold
: