【问题标题】:How to prevent non-drawing of previous pages in Navigator?如何防止在 Navigator 中不绘制以前的页面?
【发布时间】:2019-08-12 14:20:41
【问题描述】:

我在这里遇到了一个小问题:

当我将非全屏小部件推入导航器时。 之前的小部件根本不被绘制,导致背景为黑色,尽管意图是有一个简单的对话框。

如何防止这种情况发生?或者有什么简单的解决方法?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'The Dialog Issue',

      initialRoute: '/',
      routes:{
        '/': (context)=>MyHomePage(),
        '/dialog': (context)=>Dialog(child: Text('y u do dis :( and how do i change it?'))
      }
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {

  //This pushes the dialog onto the navigator.
  void _navigateToDialog(BuildContext context) {
    setState(() {
          Navigator.pushNamed(context,'/dialog');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('The Dialog issue'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Why does this happen?',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()=>_navigateToDialog(context),
        tooltip: 'do the stuff',
        child: Icon(Icons.add),
      ),
    );
  }
}

【问题讨论】:

  • 你想在那个主屏幕上显示对话框吗?
  • 问题是您有一个对话框作为路线的主要小部件。通常你不希望这样,你只想在主路由内显示对话框,它将覆盖它。查看此链接 -> coflutter.com/flutter/how-to-show-dialog-in-flutter 特别是 _showMaterialDialog 方法

标签: flutter dart


【解决方案1】:

如果您想在新屏幕上显示对话框,请使用routes中的以下内容

'/dialog': (context) => Scaffold(
              body: AlertDialog(
                title: Text("My dialog"),
                content: Text("This is body"),
                actions: <Widget>[FlatButton(onPressed: () => Navigator.pop(context), child: Text("Dismiss"))],
              ),
            ),

输出:


如果你想在主屏幕上显示Dialog,使用这个:

void _navigateToDialog(context) {
  showDialog(
    context: context,
    builder: (_) {
      return AlertDialog(
        title: Text("My dialog"),
        content: Text("This is body"),
        actions: <Widget>[FlatButton(onPressed: () => Navigator.pop(context), child: Text("Dismiss"))],
      );
    },
  );
}

输出

【讨论】:

  • 哦。我懂了!谢谢!所以问题是导航器在转换完成后不会绘制上一个东西。 (这是合理的,因为那会浪费资源)。然而,由于 ShowDialog 函数不会改变当前的路线,其他的东西会在它下面呈现。正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 2011-08-06
  • 2017-09-24
  • 2023-04-04
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
相关资源
最近更新 更多