Reputation: 35
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),
))));`
Upvotes: 1
Views: 2271
Reputation: 76
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.
Upvotes: 0
Reputation: 12673
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.
Upvotes: 2