祝你好运,当我运行flutter->窗口中的错误,如"在一个小部件的子列表中多次使用GlobalKey。"如果这是个愚蠢的问题,我很抱歉。。那我该怎么办?
我如何理解我使用"全局密钥"超过1次->我该怎么办?
代码->
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context){
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Mama',
onGenerateRoute: (settings){
switch(settings.name){
case '/home':
return PageTransition(
child: HomePage(),
type: PageTransitionType.fade
);
}
},
);
}
}
class MyHomePage extends ConsumerWidget {
GlobalKey<ScaffoldState> scaffoldState = new GlobalKey();
processLogin(BuildContext context) async{
var user = FirebaseAuth.instance.currentUser;
if(user == null){
FirebaseAuthUi.instance()
.launchAuth([AuthProvider.phone()]).then((FirebaseUser) async {
context.read().state = FirebaseAuth.instance.currentUser;
// Navigator.pushNamedAndRemoveUntil(
// context, '/home', (route) => false);
await checkLoginState(context,true);
ScaffoldMessenger.of(scaffoldState.currentContext!).showSnackBar(SnackBar(content: Text('Login Success ${FirebaseAuth.instance.currentUser?.phoneNumber}')));
}).catchError((e){
if(e is PlatformException)
if(e.code == FirebaseAuthUi.kUserCancelledError){
ScaffoldMessenger.of(scaffoldState.currentContext!).showSnackBar(SnackBar(content: Text('${e.message}')));
}
else{
ScaffoldMessenger.of(scaffoldState.currentContext!).showSnackBar(const SnackBar(content: Text('Unk Error')));
}
});
}
else{
}
}
Widget build(BuildContext context, watch){
return Scaffold(
key: scaffoldState,
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/my_bg.png'),
fit: BoxFit.cover
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children:[
Container(
padding: const EdgeInsets.all(16),
width: MediaQuery.of(context).size.width,
child:FutureBuilder(
future: checkLoginState(context,false),
builder: (context, snapshot){
if(snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator());
} else{
var userState = snapshot.data as LOGIN_STATE;
if(userState == LOGIN_STATE.LOGGED){
return Container();
}
else{
return ElevatedButton.icon(
onPressed: ()=> processLogin(context),
icon :Icon(Icons.phone, color: Colors.white,),
label: Text('LOGIN WITH ME', style: TextStyle(color:Colors.white),),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.black)),
);
}
}
}
),
)
],
),
),
);
}
Future<LOGIN_STATE> checkLoginState(BuildContext context, bool fromLogin) async {
await Future.delayed(Duration(seconds: fromLogin == true ? 0 : 3)).then((value)=>{
FirebaseAuth.instance.currentUser
?.getIdToken()
.then((token){
print('$token');
context.read().state = token;
Navigator.pushNamedAndRemoveUntil(context, '/home', (route) => false);
})
});
return FirebaseAuth.instance.currentUser != null
? LOGIN_STATE.LOGGED
: LOGIN_STATE.NOT_LOGIN;
}
}
问题:如何正确使用Globalkeys来确保每个小部件只有一个?如有任何帮助,我们将不胜感激。
没有,期待答案
您需要将全局键存储在变量中,然后在任何您想使用的地方使用变量名,请参考下面的代码,我不确定它是否会对您有所帮助,但您会从中得到一些想法。
final GlobalKey<FormState> _formKey = GlobalKey();
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
TextFormField(
decoration: const InputDecoration(labelText: 'E-Mail'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty || !value.contains('@')) {
return 'Invalid email!';
}
return null;
// return null;
},
onSaved: (value) {
_authData['email'] = value!;
},
),
),
同样,你已经写了三行这样的话,的scaffoldState.currentContext!(。此处,替换";scaffoldState";与上下文相关。