skip to Main Content

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


  1. You can use a Builder widget to provide a valid context:

    ...
    floatingActionButton: Builder(
      builder: (context) => FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => FoodScreen()),
          );
        },
        backgroundColor: Colors.green,
        child: const Icon(Icons.add),
      ),
    ),
    ...
    
    Login or Signup to reply.
  2. Because the context you pass to Navigator.push is wrong. It is the context of myapp, which isn’t stay inside your Scaffold widget.

    If you want to use Navigator, then you must pass the context that stay inside Scaffold. Try Builder to have the context stay inside Scaffold:

    Builder(
            builder: (builderContext) => FloatingActionButton(
              onPressed: () {
                Navigator.push(
                  builderContext,
                  MaterialPageRoute(builder: (builderContext) => FoodScreen()),
                );
              },
              backgroundColor: Colors.green,
              child: const Icon(Icons.add),
            ),
          )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search