A global key was used multiple times inside one widgets child list
Asked Answered
J

12

29

After closing the app, when I try to open it again, I'm getting the following error but it's only on iOS platform, Android works well.

enter image description here

I have looked around and there are several SO questions and issues about this problem but I couldn't solve it. I'm also using bloc pattern for managing state.

I have GlobalKey<FormState> in my AuthenticateForm.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:low_code/blocs/authentication/authentication_bloc.dart';
import 'package:low_code/blocs/authentication/authentication_event.dart';
import 'package:low_code/helpers/app_localization/app_localizations.dart';

class AuthenticateForm extends StatefulWidget {
  @override
  _AuthenticateFormState createState() => _AuthenticateFormState();
}

class _AuthenticateFormState extends State<AuthenticateForm> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  String username;

  String password;

  @override
  Widget build(BuildContext context) {
    AppLocalizations appLocalizations = AppLocalizations.of(context);
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          TextFormField(
            onSaved: (String value) => username = value,
            initialValue: 'dms-bpm',
            decoration: InputDecoration(
                labelText: appLocalizations.translate('username')),
            // ignore: missing_return
            validator: (String value) {
              if (value.isEmpty) {
                return 'Please enter your ${appLocalizations.translate('username')}';
              }
            },
          ),
          TextFormField(
            onSaved: (String value) => password = value,
            obscureText: true,
            decoration: InputDecoration(
                labelText: appLocalizations.translate('password')),
            initialValue: 'dms-bpm',
            // ignore: missing_return
            validator: (String value) {
              if (value.isEmpty) {
                return 'Please enter your ${appLocalizations.translate('password')}';
              }
            },
          ),
          RaisedButton(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(15))),
            child: Text(appLocalizations.translate('login')),
            onPressed: () {
              _formKey.currentState.save();
              if (_formKey.currentState.validate()) {
                BlocProvider.of<AuthenticationBloc>(context)
                  ..dispatch(
                      Authenticate(username: username, password: password));
              }
            },
          )
        ],
      ),
    );
  }
}

Flutter (Channel stable, v1.7.8+hotfix.4, on Microsoft Windows [Version 10.0.17763.615], locale en-GB)

Jesuitism answered 27/8, 2019 at 11:14 Comment(8)
each form should have only one child as i knowRaneeraney
Try to Add Key on ListView,GridView SingleChildScrollView etc.. this will solve the issue as you are using the same key for two Scroll WidgetEncore
I add key all the ListView, GridView, SingleChildScrollView but it didnt solve it. @ArunR.PrajapatiJesuitism
@MuratAslan Form already has only one child which is a columnKlehm
one textfield i meanRaneeraney
@MuratAslan So you're saying: "Each form should have only one textformfield widget". That's simply not the case and not how the forms work. Please review some form examples with Flutter medium.com/flutter-community/…Klehm
Hot Restart. Most errors are due to changes madeAuthority
Add home property in main.dart file...Futuristic
D
24

Try stop and rerun you application instead of hot reloading. That solved my problem.

Dramatics answered 26/3, 2021 at 13:11 Comment(3)
this can't be a solution. App must need a hot reload or restartSpunk
It does work @Mukta, try this option only once untill your problem gets resolved. Mine didScaffold
Still you don't have any idea about Global Key of Flutter. Notice the question. He is using a single key for multiple Widget or Screen. Either he needs to use a list of Global keys or different naming single key. Still now I am disagree with your answer. SorrySpunk
C
19

In my case this error happened because I had a initialRoute property set, while instead I should set the home property:

class RouteTestApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      //initialRoute: '/', //remove this
      home: FirstScreen(),  //this is the calling screen
      routes: {
        ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
      },
    );
  }
}
Chingchinghai answered 12/4, 2020 at 0:31 Comment(0)
W
4

i just stopped the hot reload and restarted the app it worked for me

Walkling answered 15/9, 2021 at 17:1 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewSpectroscope
G
3

In case you are getting the error when the app just started: Add '/' route to the list of routes and restart.

Gut answered 13/2, 2023 at 15:36 Comment(0)
D
1

In my case, I run the flutter app without adding home: BottomNavBar(). after getting an error I added home: BottomNavBar() and give hot reload (Command + s) which reproduce this error (A global key was used multiple times inside one widget child list). Then I just reconnect my target device and run again, which fixed my issue.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        brightness:Brightness.light,
        primaryColor: Colors.white,
        accentColor: Colors.blue,
        fontFamily: 'Poppins',
        appBarTheme: AppBarTheme(
          centerTitle: true,
        ),
      ),
      home: BottomNavBar(),
    );
  }
}
Devastation answered 23/1, 2021 at 3:59 Comment(0)
N
1

You can Try stop and rerun you application instead of hot reloading. That solved my problem. enter image description here

Nabokov answered 18/6, 2023 at 9:0 Comment(0)
S
0

Try to make your GlobalKey "final". I think the fact your global key is mutable might be creating this problem.

Shiekh answered 26/3, 2021 at 13:17 Comment(1)
it dosn't effect on code. But obviously need to declare as final.Spunk
C
0

just kill the app run (stop) and uninstall it then reinstall it again to reset the navigator state

Chen answered 3/8, 2022 at 9:38 Comment(0)
R
0

Just assign UniqueKey() to your ListView.

Rosina answered 21/2, 2023 at 10:2 Comment(0)
O
0

in my case i was forgot add async await for main()

main() async {
  await initModul();
  runApp(MyApp());
}

initModul() async {
  WidgetsFlutterBinding.ensureInitialized();

  final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();

  instance.registerLazySingleton<SharedPreferences>(
    () => sharedPreferences,
  );

  instance.registerLazySingleton<AppSettingsSharedPreferences>(
      () => AppSettingsSharedPreferences(instance()));

  // for clear preferences:
  // AppSettingsSharedPreferences appSettingsSharedPreferences =
  // instance<AppSettingsSharedPreferences>();
  // appSettingsSharedPreferences.clear();
}
Oglesby answered 26/5, 2023 at 15:49 Comment(0)
E
0

This link may help you. You need to either remove / prefix from your route names or your root route with / should be pushed before pushing current route.

https://medium.com/codechai/dont-use-to-prefix-your-routes-in-flutter-f3844ce1fdd5

Entomophilous answered 8/7 at 13:24 Comment(0)
T
-1

In my case, the calling screen in the home: property of the MaterialApp() object was returning null. After fixing it, I stopped the app and reran it.

Triple answered 20/7, 2021 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.