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

标签 flutter

我的“主要”小部件必须具有全局键。如果我使用 pushNamed 或等效项导航到它,它会生成有关小部件树中重复键的异常。我只能弹出到这个小部件,但这严重减少了我的导航选项和小部件的可重用性。

我已经包含了一个小型重现案例的源代码,运行该应用程序,单击主页上的 Login 按钮,输入 3 个字符的登录名和 3 个字符的密码,然后 Login

有什么想法吗?在没有 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(),
              )
            ],
          ),

        ),
      ),
    );
  }
}

最佳答案

当您使用 pushNamed 时,新路由将添加到现有路由之上。

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

关于flutter - 在导航中使用带有 GlobalKeys 的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247326/

相关文章:

dart - 使用 API 获取的 Flutter SliverGrid 填充

google-maps - 如何使用Flutter获取真实的方向指示? (绘制真实路线)

firebase - 检测用户是否已通过其他提供商登录

firebase - 如何在 Cloud Firestore 中执行 SQL Select?

flutter - 在 BottomNavigationBar 选项卡之间传递 StreamBuilder => 错误状态 : Stream has already been listened to

flutter ||使用 Codemagic 将 Apk 和 Ipa 发送到多个电子邮件

dart - 将 Assets 从包复制到文件系统

flutter - 快照.数据为空。我使用 for 循环来迭代 JSON 数据并创建对象实例列表

flutter - 是否可以更改默认的 Flutter 闪屏过渡?

json - 主体上带有 Json 的 HTTP POST - Flutter/Dart