Метод 'findAncestorStateOfType' был вызван на ноль в флаттер дротик - PullRequest
0 голосов
/ 16 марта 2020

Я создаю приложение, и я новичок во флаттере, дартс. У меня проблема в «контексте». Я хочу заменить страницу / экран на вкладке (). Но у меня появляется следующая ошибка:


> ══════ Exception caught by gesture ════════════════════════ The
> following NoSuchMethodError was thrown while handling a gesture: The
> method 'findAncestorStateOfType' was called on null. Receiver: null
> Tried calling: findAncestorStateOfType<NavigatorState>()

Вот мой код:

class Theorytest extends StatelessWidget {

    Widget  customcard(String testName ){
      return Padding(
        padding: EdgeInsets.all(10.0),
        child: InkWell(
          onTap: (){

                      Navigator.of(context).pushReplacement(MaterialPageRoute(

              builder: (context) => GetTestData(),
           ),
           );
          },
          child: Material(     
            borderRadius: BorderRadius.circular(50.0),
            elevation: 20.0,
            child : Container(
              child: Column(
                children : <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(5.0, 20.0, 10.0, 20.0),
                    child: Text( testName,
                    style: TextStyle(
                      fontSize: 24.0,
                    ),
                    ),
                    ),
                ],
              ),
            ),
          ),
        ),
      );
    }
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.white,
        body: ListView(
          children : <Widget>[
            customcard('Theory Test 1'),
            customcard('Theory Test 2'),
            customcard('Theory Test 3'),
            customcard('Theory Test 4'),
            customcard('Theory Test 5'),
            customcard('Theory Test 6'),
            customcard('Theory Test 7'),
            customcard('Theory Test 8'),
            customcard('Theory Test 9'),
            customcard('Theory Test 10'),
            customcard('Theory Test 11'),
            customcard('Theory Test 12'),
            customcard('Theory Test 13'),
            customcard('Theory Test 14'),
            customcard('Theory Test 15')          
          ]
        ),
      );
    }

Это ошибка кода. Я не знаю, почему контекст не работает для меня.

enter image description here

1 Ответ

0 голосов
/ 16 марта 2020

Проблема (почему контекст не работает для вас) заключается в том, что в вашей customCard метод

нет объекта BuildContext * Есть несколько способов достижения this ..

Один из способов - добавить параметр BuildContext в ваш метод. Подобно этому

  Widget customcard(BuildContext context, String testName) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: InkWell(
        onTap: () {
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (context) => GetTestData(),
            ),
          );
        },
        child: Material(
          borderRadius: BorderRadius.circular(50.0),
          elevation: 20.0,
          child: Container(
            child: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(5.0, 20.0, 10.0, 20.0),
                  child: Text(
                    testName,
                    style: TextStyle(
                      fontSize: 24.0,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

Тогда ваши потомки ListView будут выглядеть как

customCard(context, "Theory Test 1")

Еще один способ сделать это - создать виджет без состояния и вернуть пользовательскую карту в методе сборки.

class CustomCard extends StatelessWidget {
  String testName;
  CustomCard(this.testName);
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: InkWell(
        onTap: () {
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (context) => GetTestData(),
            ),
          );
        },
        child: Material(
          borderRadius: BorderRadius.circular(50.0),
          elevation: 20.0,
          child: Container(
            child: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(5.0, 20.0, 10.0, 20.0),
                  child: Text(
                    testName,
                    style: TextStyle(
                      fontSize: 24.0,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Тогда ваши потомки ListView будут похожи на ...

CustomCard("Theory Test 1")

Я надеюсь, что это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...