1

that error happen when i tried putting a method that need to take buildcontext as an argument in floating action button widget.

I tried moving the same method to different widgets that have builders and it worked fine so why don't the FA button have the parent context ? here is where it happens:

runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            title: Text('policies list'),
          ),
          body: getList(),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () => showSB(context),
          ))));`
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
bido_Boy
  • 35
  • 6

2 Answers2

2

the code you have above does not have context because you didn't create a Stateful or Stateless class for home

I think You should do this instead

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          someMethodThatTakesContextAsParameter(context);
        },
      ),
    );
  }

  void someMethodThatTakesContextAsParameter(BuildContext context){

  }
}

Hope this works for you.

Josteve
  • 11,459
  • 1
  • 23
  • 35
  • thanks a lot it worked , but it shows up a new exception that (Scaffold.of() called with a context that does not contain a Scaffold.) – bido_Boy Mar 18 '20 at 00:32
  • i found it here --> https://stackoverflow.com/questions/51304568/scaffold-of-called-with-a-context-that-does-not-contain-a-scaffold thx – bido_Boy Mar 18 '20 at 00:35
0

I know it's kinda late but for the people who are yet to face this,

You'll need use a Stateful widget if you're to use context outside the build function (can use context inside the build function . Secondly, make sure you didn't auto-import it the library 'dart:js' when trying to use context outside of the build function inside a Stateless widget.

devIbraz
  • 11
  • 1