簡體   English   中英

Flutter:未處理的異常:NoSuchMethodError:在 null 上調用了方法“findAncestorStateOfType”

[英]Flutter: Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null

每次我運行我的應用程序時,我都希望顯示徽標,然后讓它導航到登錄頁面。 但是每當它開始導航到登錄頁面時,我都會收到以下錯誤。

Restarted application in 5,721ms.
E/flutter (17103): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
E/flutter (17103): Receiver: null
E/flutter (17103): Tried calling: findAncestorStateOfType<NavigatorState>()
E/flutter (17103): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (17103): #1      Navigator.of (package:flutter/src/widgets/navigator.dart:2115:19)
E/flutter (17103): #2      Navigator.pushNamed (package:flutter/src/widgets/navigator.dart:1529:22)
E/flutter (17103): #3      _MyHomePageState.initState.<anonymous closure> (package:househunter/main.dart:96:17)
E/flutter (17103): #4      _rootRun (dart:async/zone.dart:1180:38)
E/flutter (17103): #5      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (17103): #6      _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (17103): #7      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (17103): #8      _rootRun (dart:async/zone.dart:1184:13)
E/flutter (17103): #9      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (17103): #10     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1003:23)
E/flutter (17103): #11     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter (17103): #12     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (17103): #13     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (17103): #14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (17103): 

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }
 
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Rent',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      routes: {
        LoginPage.routeName: (context) => LoginPage(),
      },
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    Timer(Duration(seconds: 2), () {
      Navigator.pushNamed(context, LoginPage.routeName); //ERROR ON THIS LINE
    });
    super.initState();
  }
  //Before we get the login page we see the name of the app for 2 seconds. below code defines this functionality
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center
        child: Column(
          //mainAxisAlignment centers the children vertically
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 150,
              width: 150,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage('assets/images/finalLogo.png')
                  )
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 10.0),
              child: Text(
                '${AppConstants.appName}',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 3.0),
              child: Text(
                'A better way to Rent',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

我看到了一個類似的帖子,上面說您的上下文從未分配過。 您正在使用該上下文調用 Navigator,而它仍然是 null。

Widget build(context) {
setState(() => this.context = context);
}

但是,當我調用 setstate() 來定義上下文時,它給了我一個錯誤“上下文”,一個最終變量,只能設置一次。 嘗試使“上下文”成為非最終的。 任何幫助將不勝感激。

試試這個例子的想法

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MaterialApp(home: AnimatedFlutterLogo()));

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(seconds: 2), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
      //<-- Navigate to loginPage on Timeout
      Navigator.push(
        //<-- Navigate to loginPage on Timeout
        context,
        MaterialPageRoute(builder: (context) => LoginPage()),
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Colors.white,
      style: _logoStyle,
    );
  }
}

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(alignment: Alignment.center, child: Text("LOG IN PAGE"));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM