如何防止在Navigator中不绘制以前的页面?

时间:2019-08-12 14:20:41

标签: flutter dart

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

当我将非全屏小部件推入导航器时。 以前的窗口小部件根本不会被绘制,导致黑色背景,即使其目的是要创建一个简单的对话框。

如何防止这种情况发生?还是一个简单的解决方法?

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),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

如果要在新屏幕上显示对话框,请在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"))],
              ),
            ),

输出:

enter image description here


如果您想在主屏幕上显示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"))],
      );
    },
  );
}

输出

enter image description here