Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

flutter - Why can't i use a condition to change page but raised button works?

I had a problem from Getting EXCEPTION CAUGHT BY WIDGETS LIBRARY & Failed assertion: line 3289 pos 12: '!_debugLocked': is not true So i decided to recreated the issue, When the increment _counter is more than 2 it would go to Home() But an error would pop up

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

void main() {
  runApp(new MaterialApp(
    home: new Greeting(),
  ));
}

class Greeting extends StatefulWidget {
  @override
  _GreetingState createState() => new _GreetingState();
}

class _GreetingState extends State<Greeting> {
  @override
  initState() {
    super.initState();
  }

  static int _counter = 0;

  void _increment() {
    setState(() {
      _counter++;
    });
  }



  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Align(
          alignment: FractionalOffset.center,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              RaisedButton(
                onPressed: _increment,
                child: Text('Increment'),
              ),
              Text('Count: $_counter'),


              RaisedButton(                      // Current Testing swap Page
                child: Text('Go to home test'),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Home()),
                  );
                },
              ),

              (_counter > 2) == true ?
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => Home()),
              ):Container()


            ],
          )),
    );
  }

}




class Home extends StatefulWidget {
  @override
  _HomeState createState() => new _HomeState();
}

class _HomeState extends State<Home> {

  initState() {
    super.initState();
    new Timer(const Duration(seconds: 5), onClose);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor: Colors.pink,
        title: new Text("Home"),
      ),
    );
  }

  void onClose() {
    Navigator.pop(context);
  }
}

Is there any reason why i can't use the condition to navigate to another page?

Launching libmain.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built buildappoutputsapkdebugapp-debug.apk.
Installing buildappoutputsapkapp.apk...
Debug service listening on ws://127.0.0.1:52775/UyFpSA2pizE=/ws
Syncing files to device Android SDK built for x86...
D/EGL_emulation( 6595): eglMakeCurrent: 0xdc91a2a0: ver 3 1 (tinfo 0xdc90f7d0)

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Greeting(dirty, state: _GreetingState#11d1e):
setState() or markNeedsBuild() called during build.

This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Overlay-[LabeledGlobalKey<OverlayState>#5fa74]
  state: OverlayState#b1e52(entries: [OverlayEntry#629a0(opaque: true; maintainState: false), OverlayEntry#de9e6(opaque: false; maintainState: true), OverlayEntry#60d55(opaque: false; maintainState: false), OverlayEntry#09442(opaque: false; maintainState: true)])
The widget which was currently being built when the offending call was made was: Greeting
  dirty
  state: _GreetingState#11d1e
The relevant error-causing widget was: 
  Greeting file:///C:/Users/18049496/AndroidStudioProjects/new_page/lib/main.dart:6:15
When the exception was thrown, this was the stack: 
#0      Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4167:11)
#1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4182:6)
#2      State.setState (package:flutter/src/widgets/framework.dart:1253:14)
#3      OverlayState.rearrange (package:flutter/src/widgets/overlay.dart:415:5)
#4      NavigatorState._flushHistoryUpdates (package:flutter/src/widgets/navigator.dart:3069:16)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
E/flutter ( 6595): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2334 pos 18: '!navigator._debugLocked': is not true.
E/flutter ( 6595): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
E/flutter ( 6595): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
E/flutter ( 6595): #2      _RouteEntry.handlePush.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2334:18)
E/flutter ( 6595): #3      TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart:398:15)
E/flutter ( 6595): #4      _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter ( 6595): #5      _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter ( 6595): #6      _FutureListener.handleValue (dart:async/future_impl.dart:141:18)
E/flutter ( 6595): #7      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
E/flutter ( 6595): #8      Future._propagateToListeners (dart:async/future_impl.dart:711:32)
E/flutter ( 6595): #9      Future._completeWithValue (dart:async/future_impl.dart:526:5)
E/flutter ( 6595): #10     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:556:7)
E/flutter ( 6595): #11     _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 6595): #12     _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 6595): #13     _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter ( 6595): #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter ( 6595): #15     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter ( 6595): #16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter ( 6595): 
E/flutter ( 6595): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3580 pos 12: '!_debugLocked': is not true.
E/flutter ( 6595): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
E/flutter ( 6595): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
E/flutter ( 6595): #2      NavigatorState.pop (package:flutter/src/widgets/navigator.dart:3580:12)
E/flutter ( 6595): #3      Navigator.pop (package:flutter/src/widgets/navigator.dart:2010:27)
E/flutter ( 6595): #4      _HomeState.onClose (package:newpage/main.dart:100:15)
E/flutter ( 6595): #5      _rootRun (dart:async/zone.dart:1180:38)
E/flutter ( 6595): #6      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 6595): #7      _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter ( 6595): #8      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter ( 6595): #9      _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 6595): #10     _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 6595): #11     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1003:23)
E/flutter ( 6595): #12     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter ( 6595): #13     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter ( 6595): #14     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter ( 6595): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter ( 6595): 

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add that navigator code into _increment function.

void _increment() {
setState(() {
  _counter++;
});
if (_counter > 2) {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => Home()),
  );
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...