Skip to content

Global key is getting reused in navigator #10154

@123qws

Description

@123qws

This is happening when I pop the route and then push a new route which uses as same global key in the old route.

Here is a simple example:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap:() {
        Navigator.push(context, new MaterialPageRoute(builder: (_) => new Company(0)));
      },
      child: new Text('go to company'));
  }
}

class Company extends StatelessWidget {
  static final _scaffoldKey = new GlobalKey<ScaffoldState>();
  final int companyId;
  Company(this.companyId);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      body: new Column(children: [
        new Text('Company $companyId'),
        new GestureDetector(
          onTap:() {
            Navigator.pop(context);
            Navigator.push(context,
              new MaterialPageRoute(builder: (_) => new Company(companyId+1)));
          },
          child: new Text('next company')),
      ]
    ));
  }
}

Clicks "go to company" and then clicks "next company", you will see

I/flutter ( 8026): The following assertion was thrown building Company():
I/flutter ( 8026): Multiple widgets used the same GlobalKey.
I/flutter ( 8026): The key [LabeledGlobalKey<ScaffoldState>#33415169] was used by multiple widgets. The parents of
I/flutter ( 8026): those widgets were different widgets that both had the following description:
I/flutter ( 8026):   Company()
I/flutter ( 8026): A GlobalKey can only be specified on one widget at a time in the widget tree.

It seems that the popped route did not remove the global key from the widget tree.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions