在导航中使用带有GlobalKeys的小部件

时间:2019-07-29 04:44:28

标签: flutter

我的“主”窗口小部件必须具有全局密钥。如果使用pushNamed或等效名称导航到它,它将在小部件树中生成有关重复键的异常。我只能pop到此小部件,但这严重降低了我的导航选项和小部件的可重用性。

我提供了一个小复制案例的来源,运行该应用程序,单击主页上的Login按钮,输入3个字符的登录名和3个字符的密码,然后输入Login。 / p>

有什么想法吗?没有GlobalKey的重新设计是一项艰巨的任务。

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown while finalizing the widget tree:
flutter: Duplicate GlobalKey detected in widget tree.
flutter: The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of
flutter: the widget tree being truncated unexpectedly, because the second time a key is seen, the previous
flutter: instance is moved to the new location. The key was:
flutter: - [GlobalKey#1c91e navKey]
flutter: This was determined by noticing that after the widget with the above global key was moved out of its
flutter: previous parent, that previous parent never updated during this frame, meaning that it either did
flutter: not update at all or updated before the widget was moved, in either case implying that it still
flutter: thinks that it should have a child with that global key.
flutter: The specific parent that did not update after having one or more children forcibly removed due to
flutter: GlobalKey reparenting is:
flutter: - Semantics(container: false, properties: SemanticsProperties, label: null, value: null, hint: null,
flutter: hintOverrides: null, renderObject: RenderSemanticsAnnotations#147f5 NEEDS-PAINT)
flutter: A GlobalKey can only be specified on one widget at a time in the widget tree.
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      BuildOwner.finalizeTree.<anonymous closure> 
flutter: #1      BuildOwner.finalizeTree 
flutter: #2      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame 
flutter: #3      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback 
flutter: #4      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback 
flutter: #5      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame 
flutter: #6      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame 
flutter: #10     _invoke  (dart:ui/hooks.dart:236:10)
flutter: #11     _drawFrame  (dart:ui/hooks.dart:194:3)
flutter: (elided 3 frames from package dart:async)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: Multiple widgets used the same GlobalKey.
import 'package:flutter/material.dart';

class MyKeys {
  static final GlobalKey navKey = GlobalKey<NavigatorState>(debugLabel: 'navKey');
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        "/": (_) => MyHomePage(key: MyKeys.navKey, title: 'Home Page'),
        '/auth': (_) => MyAuth(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              child: Text('Login'),
              onPressed: () => Navigator.of(context).pushNamed('/auth'),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class MyAuth extends StatefulWidget {
  @override
  _MyAuthState createState() => _MyAuthState();
}

class _MyAuthState extends State<MyAuth> {
  String login;
  String password;
  final _formKey = GlobalKey<FormState>();

  void _doLogin() {
    final form = _formKey.currentState;
    if(form.validate()) {
      form.save();
      Navigator.of(context).pushNamed('/');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Login')),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Enter login',
                ),
                autocorrect: false,
                autofocus: true,
                validator: (v) => v.trim().length < 3 ? 'Enter more than 3 chars': null,
                onSaved: (v) => login = v.trim(),
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Enter password',
                ),
                obscureText: true,
                autocorrect: false,
                validator: (v) => v.trim().length < 3 ? 'Password should be no less than 3 chars': null,
                onSaved: (v) => password = v.trim(),
              ),
              FlatButton(
                child: Text('Login'),
                onPressed: () => _doLogin(),
              )
            ],
          ),

        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

使用pushNamed时,新路由会添加到现有路由的顶部。

您可以使用pushReplacementNamed而不是pushNamed,因此现有的窗口小部件将从导航堆栈中删除,并用新的替换。