Flutter says that context is undefined in the 2nd last line of the following code:
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: TextButton(
style: TextButton.styleFrom(backgroundColor: title == "Clock" ? Colors.red: Colors.transparent),
onPressed: () {
var menuInfo = Provider.of<MenuInfo>(context);
},
But, I already have defined context in my main.dart as follows:
@override
Widget build(BuildContext context){
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ChangeNotifierProvider<MenuInfo>(
create: (context) => MenuInfo(MenuType.clock, "null", "null"),
child: HomePage()),
);
Why is Flutter saying that I have not defined context?
CodePudding user response:
I assume that you place the padding thing code outside build. So, in this case you will need to parse context too in your parameter.
MenuInfo(MenuType.clock, "null", "null", context)
Widget MenuInfo(...., BuildContex context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: TextButton(
style: TextButton.styleFrom(backgroundColor: title == "Clock" ? Colors.red:
Colors.transparent),
onPressed: () {
var menuInfo = Provider.of<MenuInfo>(context);
},
... }
CodePudding user response:
Note: This problem has been solved. If creating a function or widget outside a class that extends stateless or stateful widgets, BuildContext must be passed in as a parameter during declaration as shown here:
Widget BuildButton(String title, String img, BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: TextButton(
style: TextButton.styleFrom(backgroundColor: title == "Clock" ? Colors.red: Colors.transparent),
onPressed: () {
var menuInfo = Provider.of<MenuInfo>(context);
},
child: Column(
children: <Widget>[
Image.asset(img, scale: 1.5,),
SizedBox(height: 6),
Text(
title,
style: TextStyle(fontFamily: 'avenir',color: Colors.white, fontSize: 14),
),
]
),
),
);
}