Избегайте множественных исключений setPreferredOrientations () - PullRequest
1 голос
/ 05 апреля 2020

Я пытаюсь настроить устройство на предпочтительную ориентацию, когда пользователь использует определенную страницу c в моем проекте Flutter. Мой код работает, но когда я пу sh 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')),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...