I am using a provider pattern to separate UI codes and business logic codes. It works great, but the codes are getting longer because of keep writing 'context.read<>' and 'context.watch<>' to use provider codes. Therefore, I want to make a variable to avoid writing 'context.read<>' and 'context.watch<>'. For example
isSignup = context.watch<LoginSignupData>().isSignup
However, it makes an error that 'Undefined name 'context'.' Why this error happens and how can I fix this problem? Thank you!
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../Store/loginSignupData.dart';
import '../../main.dart';
class LoginSignupSendingButton extends StatelessWidget {
LoginSignupSendingButton({Key? key}) : super(key: key);
var isSignup = context.read<LoginSignupData>().isSignup; //error
@override
Widget build(BuildContext context) {
return AnimatedPositioned(
duration: const Duration(milliseconds: 500),
curve: Curves.easeIn,
top: context.watch<LoginSignupData>().isSignup ? 520 : 470,
right: 0,
left: 0,
child: Center(
child: Container(
padding: const EdgeInsets.all(15),
height: 90,
width: 90,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(50)),
child: GestureDetector(
onTap: () {
print('isSignup : ${context.read<LoginSignupData>().isSignup}');
context.read<LoginSignupData>().isSignup ?
context.read<LoginSignupData>().signUp(context) : context.read<LoginSignupData>().signIn(context);
final isValid = context.read<LoginSignupData>().formKey.currentState!.validate();
if (context.read<LoginSignupData>().isSignupValid && isValid) {
context.read<LoginSignupData>().formKey.currentState!.save();
Navigator.push(context, MaterialPageRoute(builder: (context) => const MyApp()));
}
},
child: Container(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Colors.orange, Colors.red],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
borderRadius: BorderRadius.circular(30),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
spreadRadius: 1,
blurRadius: 1,
offset: const Offset(0, 1),
),
],
),
child: const Icon(
Icons.arrow_forward,
color: Colors.white,
),
),
),
),
),
);
}
}
CodePudding user response:
Try below code, declare isSignip
inside build
method hope its help.
@override
Widget build(BuildContext context) {
var isSignup = context.read<LoginSignupData>().isSignup;
return ...;
}