Как исправить трепетание черного экрана при навигации?

Я создаю многостраничное приложение на флаттере. Когда я использую в нем навигацию, у меня черный экран.


    import 'package:flutter/material.dart';
    
    
    void main() => runApp(MyHomePage());
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Page0(),
        );
      }
    }
    
    class Page0 extends StatefulWidget {
      @override
      _Page0State createState() => _Page0State();
    }
    
    class _Page0State extends State {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Color(0xFF493597),
          body: ListView(
            children: [
              Padding(
                padding: EdgeInsets.only(top: 15.0, left: 10.0),
              ),
              SizedBox(
                height: 25.0,
              ),
              Padding(
                padding: EdgeInsets.only(left: 40.0),
                child: Row(
                  children: [
                    Text(
                      'Expense',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 25.0),
                    ),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      'What',
                      style: TextStyle(
                        fontFamily: 'Montserrat',
                        color: Colors.white,
                        fontSize: 25.0,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 60.0),
              Container(
                margin: EdgeInsets.only(
                  left: 10.0,
                  right: 10.0,
                ),
                height: MediaQuery.of(context).size.height - 150,
                decoration: BoxDecoration(
                  color: Color(0xFFFCFCFC),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(75.0),
                    topRight: Radius.circular(75.0),
                  ),
                ),
                child: ListView(
                  primary: false,
                  padding: EdgeInsets.only(
                    left: 15.0,
                    right: 20.0,
                    top: 25.0,
                  ),
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(
                        top: 30.0,
                      ),
                      child: Column(
                        children: [
                          //greeting text
                          Row(
                            children: [
                              Expanded(
                                child: Center(
                                  child: Text(
                                    'Hello! :)',
                                    style: TextStyle(
                                      fontFamily: 'Permanent-Marker',
                                      color: Colors.black,
                                      fontSize: 30.0,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
    
                          SizedBox(
                            height: 30.0,
                          ),
    
                          //add button
                          Row(children: [
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: 100.0,
                                width: 100.0,
                                child: FittedBox(
                                  child: FloatingActionButton(
                                    elevation: 10.0,
                                    backgroundColor: Colors.white,
                                    child: Icon(
                                      Icons.add,
                                      color: Colors.black,
                                    ),
                                    onPressed: () {
                                       Navigator.push(context,MaterialPageRoute(builder: (context) => NewTrip()),);
                                    },
                                  ),``
                                ),
                              ),
                            ),
    
                            //add text
                            Expanded(
                              flex: 1,
                              child: Text(
                                'New trip',
                                style: TextStyle(
                                  fontFamily: 'Nanum',
                                  fontSize: 30.0,
                                ),
                              ),
                            ),
                          ]),
    
                          SizedBox(
                            height: 30.0,
                          ),
    
                          //previous trip button
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: 100.0,
                                  width: 100.0,
                                  child: FittedBox(
                                    child: FloatingActionButton(
                                      elevation: 10.0,
                                      backgroundColor: Colors.white,
                                      onPressed: () {},
                                      child: Icon(
                                        Icons.assessment,
                                        color: Colors.black,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
    
                              //previous trip text
                              Expanded(
                                flex: 1,
                                child: Text(
                                  'Previous trips',
                                  style: TextStyle(
                                    fontFamily: 'Nanum',
                                    fontSize: 30.0,
                                  ),
                                ),
                              )
                            ],
                          ),
    
                          SizedBox(
                            height: 50.0,
                          ),  
                          
    
                         
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      }
    }

А виджет NewTrip выглядит следующим образом


    class NewTrip extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(      
                  body: Text('NEW TRIP'),
                ),
        );
      }
    }

Домашняя страница загружается нормально, но как только я нажимаю кнопку новой поездки, появляется черный экран. Возможно, есть проблема с MaterialApp или Scaffold, но я пока не могу ее исправить. Может кто подскажет, в чем проблема и как исправить?

Обновлен полный код, как просили в комментариях.


person Shahbaz    schedule 24.04.2020    source источник
comment
на физическом устройстве? или симулятор?   -  person Sandeep Sharma    schedule 24.04.2020
comment
На физическом устройстве   -  person Shahbaz    schedule 24.04.2020
comment
Коды, которые приведены в вопросе, слишком минимальны ... Возможно, это из метода NewTrip build, но это не ясно!   -  person Saman Salehi    schedule 24.04.2020
comment
Пожалуйста, предоставьте дополнительный код из соответствующих виджетов. Буду рад помочь :)   -  person Sunit Gautam    schedule 24.04.2020
comment
Я обновил полный код.   -  person Shahbaz    schedule 24.04.2020
comment
Удалите MaterialApp из NewTrip и повторите попытку.   -  person Saman Salehi    schedule 24.04.2020
comment
Нет .. не работает   -  person Shahbaz    schedule 25.04.2020
comment
пожалуйста, проверьте последний ответ   -  person Salim Murshed    schedule 09.09.2020
comment
Отвечает ли это вашему требованию?   -  person Salim Murshed    schedule 30.09.2020
comment
Отвечает ли это на ваш вопрос? Flutter Navigator.pop (context) возвращает черный экран   -  person Paresh Mangukiya    schedule 20.10.2020


Ответы (10)


Итак, в NewTrip() удалите MaterialApp, поскольку он наследуется от родителя. Просто верните Scaffold.

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(      
       body: Text('NEW TRIP'),
    );
  }
}
person Shreyas C R    schedule 30.04.2020

Удалите MaterialApp()

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  Scaffold(      
       body: Text('NEW TRIP'),    
    );
  }
}
person Niteesh    schedule 29.06.2020

Пожалуйста, проверьте полное редактирование кода из вашего кода. На самом деле вы используете два FloatingActionButton. Поэтому вам нужно использовать два heroTag с разными именами. Я уже добавил в код. Нет проблем с классом NewTrip.

import 'package:flutter/material.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Page0(),
    );
  }
}

class Page0 extends StatefulWidget {
  @override
  _Page0State createState() => _Page0State();
}

class _Page0State extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF493597),
      body: ListView(
        children: [
          Padding(
            padding: EdgeInsets.only(top: 15.0, left: 10.0),
          ),
          SizedBox(
            height: 25.0,
          ),
          Padding(
            padding: EdgeInsets.only(left: 40.0),
            child: Row(
              children: [
                Text(
                  'Expense',
                  style: TextStyle(
                      fontFamily: 'Montserrat',
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 25.0),
                ),
                SizedBox(
                  width: 10.0,
                ),
                Text(
                  'What',
                  style: TextStyle(
                    fontFamily: 'Montserrat',
                    color: Colors.white,
                    fontSize: 25.0,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 60.0),
          Container(
            margin: EdgeInsets.only(
              left: 10.0,
              right: 10.0,
            ),
            height: MediaQuery.of(context).size.height - 150,
            decoration: BoxDecoration(
              color: Color(0xFFFCFCFC),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(75.0),
                topRight: Radius.circular(75.0),
              ),
            ),
            child: ListView(
              primary: false,
              padding: EdgeInsets.only(
                left: 15.0,
                right: 20.0,
                top: 25.0,
              ),
              children: [
                Padding(
                  padding: const EdgeInsets.only(
                    top: 30.0,
                  ),
                  child: Column(
                    children: [
                      //greeting text
                      Row(
                        children: [
                          Expanded(
                            child: Center(
                              child: Text(
                                'Hello! :)',
                                style: TextStyle(
                                  fontFamily: 'Permanent-Marker',
                                  color: Colors.black,
                                  fontSize: 30.0,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      SizedBox(
                        height: 30.0,
                      ),

                      //add button
                      Row(children: [
                        Expanded(
                          flex: 1,
                          child: Container(
                            height: 100.0,
                            width: 100.0,
                            child: FittedBox(
                              child: FloatingActionButton(
                                heroTag: "btn",
                                elevation: 10.0,
                                backgroundColor: Colors.white,
                                child: Icon(
                                  Icons.add,
                                  color: Colors.black,
                                ),
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => NewTrip()),
                                  );
                                },
                              ),
                            ),
                          ),
                        ),

                        //add text
                        Expanded(
                          flex: 1,
                          child: Text(
                            'New trip',
                            style: TextStyle(
                              fontFamily: 'Nanum',
                              fontSize: 30.0,
                            ),
                          ),
                        ),
                      ]),

                      SizedBox(
                        height: 30.0,
                      ),

                      //previous trip button
                      Row(
                        children: [
                          Expanded(
                            flex: 1,
                            child: Container(
                              height: 100.0,
                              width: 100.0,
                              child: FittedBox(
                                child: FloatingActionButton(
                                  heroTag: "btn1",
                                  elevation: 10.0,
                                  backgroundColor: Colors.white,
                                  onPressed: () {},
                                  child: Icon(
                                    Icons.assessment,
                                    color: Colors.black,
                                  ),
                                ),
                              ),
                            ),
                          ),

                          //previous trip text
                          Expanded(
                            flex: 1,
                            child: Text(
                              'Previous trips',
                              style: TextStyle(
                                fontFamily: 'Nanum',
                                fontSize: 30.0,
                              ),
                            ),
                          )
                        ],
                      ),

                      SizedBox(
                        height: 50.0,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

NewTrip класс

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('NEW TRIP'),
    );
  }
}
person Salim Murshed    schedule 09.09.2020

Итак, после некоторого исследования в Интернете я обнаружил, что проблема вызывает FloatingActionButton.

Я заменил FloatingActionButton на MaterialButton, и это устранило мою проблему.

person Shahbaz    schedule 25.04.2020
comment
Если вы все еще хотите использовать плавающую кнопку, добавьте свойство плавающей кнопки под названием herotag. У меня это работает. ???? - person Sanket Vekariya; 03.05.2020
comment
Да, в этом проблема, FloatingActionButton - это виджет-герой с тегом героя по умолчанию, вы используете на экране 2 элемента FloatingActionButton без явного указания им тега heroTag. Таким образом, Flutter не может сказать, какого героя перейти к следующему экрану, поскольку есть 2 виджета героя с одинаковым тегом. Итак, добавьте уникальный heroTag для вас обоих FloatingActionButton, как этот, в свой FloatingActionButton. - person Taha Malik; 28.11.2020
comment
Кроме того, удалите приложение MaterialApp, нет смысла использовать 2 приложения с материалами в одном приложении flutter. - person Taha Malik; 28.11.2020
comment
Также, пожалуйста, примите ваш ответ как правильный, чтобы другие не пытались ответить на него. - person Taha Malik; 28.11.2020

Проблема в том, что вы используете materialApp внутри другого materialApp

Навигатор просто меняет страницы, и нам не нужно отдельное приложение materialApp в NewTrip ().

Итак, NewTrip должен быть следующим

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('NEW TRIP'),
    );
  }
}
person Akshit Ostwal    schedule 21.11.2020

Используйте ThemeData вместе с параметром scaffoldBackgroundColor.
Для пример:

ThemeData (
   scaffoldBackgroundColor: Colors.black,
)
person Felipe Sales    schedule 18.01.2021

В моем случае это вызвано:

// to set portait screen orientation 
SystemChrome.setPreferredOrientation([
   DeviceOrientation.portraitUp,
   DeviceOrientation.portraitDown,
]);
// Instead i use `android:screenOrientation="portrait"` on my AndroidManifest.xml.

Это я объявил при рендеринге виджета страницы. Удалено, решило мою проблему с черным экраном.

person Zorro    schedule 01.04.2021

FloatingActionButton - это проблема, поэтому, если вы действительно хотите использовать кнопку с плавающим действием, вы должны добавить каждую из них в уникальный heroTag. Теперь вы сможете без проблем использовать FloatingActionButton. Никогда не используйте более одной плавающей кнопки действия, не используя HeroTag на одной странице.

person gsm    schedule 19.04.2021

Я считаю, что во всем приложении Flutter может быть только один виджет MaterialApp, потому что виджет MaterialApp, вероятно, будет основным или основным компонентом Flutter. Поэтому, когда вы пытаетесь перейти на новый экран, попробуйте вернуть виджет Scaffold вместо виджета MaterialApp.

class NewTrip extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(      
                  body: Text('NEW TRIP'),
        );
      }
    }
person Kavya S    schedule 29.05.2021

Измените scaffoldBackgroundColor

theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.white,  //here
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),

class NewTrip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('NEW TRIP'),
    );
  }
}
person Rasel Khan    schedule 24.12.2020