避免setPreferredOrientations()多个键异常

问题描述 投票:1回答:1

当用户使用我的Flutter项目中的特定页面时,我试图使设备的首选方向变为横向。我的代码有效,但是当我按PageOne显示它时,会收到很多异常:

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
Multiple widgets used the same GlobalKey.

The key [GlobalKey#a3ef0] was used by multiple widgets. The parents of those widgets were:
- AnimatedBuilder(animation: AnimationController#c2d69(⏭ 1.000; paused), dependencies: [MediaQuery])
- AnimatedBuilder(animation: AnimationController#c2d69(⏭ 1.000; paused), dependencies: [MediaQuery], state: _AnimatedState#5b6e5)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack
#0      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure>.<anonymous closure> 
package:flutter/…/widgets/framework.dart:246
#1      _LinkedHashMapMixin.forEach  (dart:collection-patch/compact_hash.dart:379:8)
#2      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure> 
package:flutter/…/widgets/framework.dart:193
#3      _LinkedHashMapMixin.forEach  (dart:collection-patch/compact_hash.dart:379:8)
#4      GlobalKey._debugVerifyGlobalKeyReservation.<anonymous closure> 
package:flutter/…/widgets/framework.dart:189
...
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════
Launching lib/main.dart on iPhone 11 Pro in debug mode...

════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════

这是我的HomePage实现

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
          itemCount: 100,
          itemBuilder: (context, index) {
            return CupertinoContextMenu(
              child: Container(
                margin: const EdgeInsets.all(10),
                color: Colors.yellow,
                height: 30,
                width: 200,
              ),
              actions: <Widget>[
                CupertinoContextMenuAction(
                  child: const Text('Action one'),
                  onPressed: () async => await Navigator.of(context)
                      .push(MaterialPageRoute(builder: (context) => PageOne())),
                ),
              ],
            );
          }),
    );
  }
}

这是我首选的定向页面

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  @override
  void initState() {
    super.initState();

    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations(DeviceOrientation.values);
    super.dispose();
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Page One')),
    );
  }
}
flutter dart flutter-layout
1个回答
0
投票

您可以在下面复制粘贴运行完整代码您可以在Navigator.pop(context);之后使用Navigator.of(context).push

代码段

CupertinoContextMenuAction(
                  child: const Text('Action one'),
                  onPressed: () async {
                    await Navigator.of(context).push(
                        MaterialPageRoute(builder: (context) => PageOne()));
                    Navigator.pop(context);
                  },
                ),

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';

class PageOne extends StatefulWidget {
  @override
  _PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  @override
  void initState() {
    super.initState();

    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations(DeviceOrientation.values);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Page One')),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
          itemCount: 100,
          itemBuilder: (context, index) {
            return CupertinoContextMenu(
              child: Container(
                margin: const EdgeInsets.all(10),
                color: Colors.yellow,
                height: 30,
                width: 200,
              ),
              actions: <Widget>[
                CupertinoContextMenuAction(
                  child: const Text('Action one'),
                  onPressed: () async {
                    await Navigator.of(context).push(
                        MaterialPageRoute(builder: (context) => PageOne()));
                    Navigator.pop(context);
                  },
                ),
              ],
            );
          }),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.