Flutter:类型 'Future<dynamic>' 不是类型 'Widget' 的子类型 // MaterialPageRoute<dynamic>(null))

Posted

技术标签:

【中文标题】Flutter:类型 \'Future<dynamic>\' 不是类型 \'Widget\' 的子类型 // MaterialPageRoute<dynamic>(null))【英文标题】:Flutter: type 'Future<dynamic>' is not a subtype of type 'Widget' // MaterialPageRoute<dynamic>(null))Flutter:类型 'Future<dynamic>' 不是类型 'Widget' 的子类型 // MaterialPageRoute<dynamic>(null)) 【发布时间】:2020-12-29 09:19:37 【问题描述】:

我正在尝试导航到相机屏幕,当我触发导航时出现错误

Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'Widget'
Another exception was thrown: setState() or markNeedsBuild() called during build.

错误指向我来自上一页的导航。

我也在那里看到了这个错误

The AnimationController notifying status listeners was: AnimationController#a911e(⏮ 0.000; paused; for MaterialPageRoute<dynamic>(null))
onTap: () => Navigator.push(
   context,
  MaterialPageRoute(
    builder: (context) => CameraScreen())),

这是得到错误的函数

captureImageWithCamera() async 
    Navigator.pop(this.context);
    File imageFile = await ImagePicker.pickImage(
      source: ImageSource.camera,
      maxHeight: 680,
      maxWidth: 970,
    );
    if (imageFile != null) 
      //imageFile = await cropImage(imageFile);
      setState(() 
        //this.file = imageFile as File;
        print(file);
      );
      await controller.dispose();
    
  

为了完整的上下文,这里是从调用导航到相机屏幕的第一页的完整构建器。您将在其中看到到 CameraScreen 的导航。

createStoryView() 
    return FutureBuilder(
      future: usersReference.document(currentOnlineUserId).get(),
      builder: (context, dataSnapshot) 
        if (!dataSnapshot.hasData) 
          return circularProgress();
         else 
          User user = User.fromDocument(dataSnapshot.data);
          return Material(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(0.0),
                  child: Card(
                    color: Colors.white,
                    elevation: 0.0,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ListTile(
                        leading: Stack(
                          children: <Widget>[
                            GestureDetector(
                              child: Padding(
                                padding: EdgeInsets.only(top: 0.0, bottom: 0.0),
                                child: user.photoUrl.isNotEmpty
                                    ? CircleAvatar(
                                        radius: 30.0,
                                        backgroundColor: Colors.grey,
                                        backgroundImage:
                                            CachedNetworkImageProvider(
                                                user.photoUrl),
                                      )
                                    : CircleAvatar(
                                        radius: 30.0,
                                        backgroundColor: Colors.grey,
                                      ),
                              ),
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => StoryPageView())),
                            ),
                          ],
                        ),
                        title: Text(
                          user.profileName,
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        subtitle: Text("Add a Story"),
                        onTap: () => Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => CameraScreen())),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "Viewed Stories",
                    style: TextStyle(
                      color: Colors.grey,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.all(0.0),
                    color: Colors.white,
                    child: ListView(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ListTile(
                            leading: CircleAvatar(
                              radius: 30.0,
                              backgroundColor: Colors.grey,
                            ),
                            title: Text(
                              "Username",
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            subtitle: Text("Timestamp"),
                            onTap: () => Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => StoryPageView())),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        
      ,
    );
  

这里是 CameraPage 的构建器

@override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        iconTheme: IconThemeData(color: Colors.blue),
        title: Text(
          "Story Post",
          style: TextStyle(
            color: Colors.blue,
            fontSize: 22.0,
          ),
        ),
      ),
      body: file == null ? captureImageWithCamera() : displayStoryUploadScreen(),
    );
  

这是完整的错误信息

══╡ EXCEPTION CAUGHT BY ANIMATION LIBRARY ╞═════════════════════════════════════════════════════════
The following assertion was thrown while notifying status listeners for AnimationController:
setState() or markNeedsBuild() called during build.
This _ModalScope<dynamic> 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:
  _ModalScope<dynamic>-[LabeledGlobalKey<_ModalScopeState<dynamic>>#0c8ee]
The widget which was currently being built when the offending call was made was:
  CameraScreen
When the exception was thrown, this was the stack:
[38;5;244m#0      Element.markNeedsBuild.<anonymous closure>[39;49m
[38;5;244m#1      Element.markNeedsBuild[39;49m
[38;5;244m#2      State.setState[39;49m
[38;5;244m#3      _ModalScopeState._routeSetState[39;49m
[38;5;244m#4      ModalRoute.setState[39;49m
[38;5;244m#5      ModalRoute.changedInternalState[39;49m
[38;5;244m#6      TransitionRoute._handleStatusChanged[39;49m
[38;5;244m#7      AnimationLocalStatusListenersMixin.notifyStatusListeners[39;49m
[38;5;244m#8      AnimationController._checkStatusChanged[39;49m
[38;5;244m#9      AnimationController._animateToInternal[39;49m
[38;5;244m#10     AnimationController.reverse[39;49m
[38;5;244m#11     TransitionRoute.didPop[39;49m
[38;5;244m#12     LocalHistoryRoute.didPop[39;49m
[38;5;244m#13     _RouteEntry.pop[39;49m
[38;5;244m#14     NavigatorState.pop[39;49m
[38;5;244m#15     Navigator.pop[39;49m
[38;5;248m#16     _CameraScreenState.captureImageWithCamera[39;49m
[38;5;248m#17     _CameraScreenState.build[39;49m
[38;5;244m#18     StatefulElement.build[39;49m
[38;5;244m#19     ComponentElement.performRebuild[39;49m
[38;5;244m#20     StatefulElement.performRebuild[39;49m
[38;5;244m#21     Element.rebuild[39;49m
[38;5;244m#22     ComponentElement._firstBuild[39;49m
[38;5;244m#23     StatefulElement._firstBuild[39;49m
[38;5;244m#24     ComponentElement.mount[39;49m
...     Normal element mounting (24 frames)
[38;5;244m#48     Element.inflateWidget[39;49m
[38;5;244m#49     MultiChildRenderObjectElement.mount[39;49m
...     Normal element mounting (136 frames)
[38;5;244m#185    Element.inflateWidget[39;49m
[38;5;244m#186    Element.updateChild[39;49m
[38;5;244m#187    RenderObjectElement.updateChildren[39;49m
[38;5;244m#188    MultiChildRenderObjectElement.update[39;49m
[38;5;244m#189    Element.updateChild[39;49m
[38;5;244m#190    ComponentElement.performRebuild[39;49m
[38;5;244m#191    StatefulElement.performRebuild[39;49m
[38;5;244m#192    Element.rebuild[39;49m
[38;5;244m#193    StatefulElement.update[39;49m
[38;5;244m#194    Element.updateChild[39;49m
[38;5;244m#195    ComponentElement.performRebuild[39;49m
[38;5;244m#196    Element.rebuild[39;49m
[38;5;244m#197    ProxyElement.update[39;49m
[38;5;244m#198    _InheritedNotifierElement.update[39;49m
[38;5;244m#199    Element.updateChild[39;49m
[38;5;244m#200    SingleChildRenderObjectElement.update[39;49m
[38;5;244m#201    Element.updateChild[39;49m
[38;5;244m#202    ComponentElement.performRebuild[39;49m
[38;5;244m#203    StatefulElement.performRebuild[39;49m
[38;5;244m#204    Element.rebuild[39;49m
[38;5;244m#205    StatefulElement.update[39;49m
[38;5;244m#206    Element.updateChild[39;49m
[38;5;244m#207    SingleChildRenderObjectElement.update[39;49m
[38;5;244m#208    Element.updateChild[39;49m
[38;5;244m#209    SingleChildRenderObjectElement.update[39;49m
[38;5;244m#210    Element.updateChild[39;49m
[38;5;244m#211    ComponentElement.performRebuild[39;49m
[38;5;244m#212    Element.rebuild[39;49m
[38;5;244m#213    StatelessElement.update[39;49m
[38;5;244m#214    Element.updateChild[39;49m
[38;5;244m#215    ComponentElement.performRebuild[39;49m
[38;5;244m#216    Element.rebuild[39;49m
[38;5;244m#217    ProxyElement.update[39;49m
[38;5;244m#218    Element.updateChild[39;49m
[38;5;244m#219    ComponentElement.performRebuild[39;49m
[38;5;244m#220    StatefulElement.performRebuild[39;49m
[38;5;244m#221    Element.rebuild[39;49m
[38;5;244m#222    BuildOwner.buildScope[39;49m
[38;5;244m#223    WidgetsBinding.drawFrame[39;49m
[38;5;244m#224    RendererBinding._handlePersistentFrameCallback[39;49m
[38;5;244m#225    SchedulerBinding._invokeFrameCallback[39;49m
[38;5;244m#226    SchedulerBinding.handleDrawFrame[39;49m
[38;5;244m#227    SchedulerBinding._handleDrawFrame[39;49m
[38;5;244m#231    _invoke  (dart:ui/hooks.dart:253:10)[39;49m
[38;5;244m#232    _drawFrame  (dart:ui/hooks.dart:211:3)[39;49m
(elided 3 frames from dart:async)
The AnimationController notifying status listeners was:
  AnimationController#ac0aa(⏮ 0.000; paused; for MaterialPageRoute<dynamic>(null))
════════════════════════════════════════════════════════════════════════════════════════════════════

[38;5;248m════════ Exception caught by animation library ═════════════════════════════════[39;49m
[38;5;244mThe following assertion was thrown while notifying status listeners for AnimationController:[39;49m
setState() or markNeedsBuild() called during build.

[38;5;244mThis _ModalScope<dynamic> 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.[39;49m
[38;5;244mThe widget on which setState() or markNeedsBuild() was called was: _ModalScope<dynamic>-[LabeledGlobalKey<_ModalScopeState<dynamic>>#0c8ee][39;49m
    [38;5;244mstate: _ModalScopeState<dynamic>#b0964[39;49m
[38;5;244mThe widget which was currently being built when the offending call was made was: CameraScreen[39;49m
    [38;5;244mdirty[39;49m
    [38;5;244mstate: _CameraScreenState#54b04[39;49m
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0      Element.markNeedsBuild.<anonymous closure>[39;49m
[38;5;244m#1      Element.markNeedsBuild[39;49m
[38;5;244m#2      State.setState[39;49m
[38;5;244m#3      _ModalScopeState._routeSetState[39;49m
[38;5;244m#4      ModalRoute.setState[39;49m
[38;5;244m...[39;49m
[38;5;244mThe AnimationController notifying status listeners was: AnimationController#ac0aa(⏮ 0.000; paused; for MaterialPageRoute<dynamic>(null))[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m
Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'Widget'

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
type 'Future<dynamic>' is not a subtype of type 'Widget'
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mCameraScreen[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

【问题讨论】:

请发布完整的错误代码。它通常包括错误发生位置的信息 好的,我刚刚添加了它@lenz 【参考方案1】:

MaterialPageRoutebuilder 函数应该从 StatelessWidgetStatefullWidget 返回一个 Widget 或类,显然 CameraScreen 都不是。

您的captureImageWithCamera 确实会返回一个Future&lt;void&gt;,但scaffoldbody 必须是一个小部件,也不清楚displayStoryUploadScreen 的返回类型是什么,但也必须是一个小部件。

如果您需要未来的价值来构建您的小部件,您需要使用FutureBuilder 来等待它,而无需查看渲染树。

【讨论】:

我添加了实现相机屏幕的小部件。我不想添加整个页面,因为那里有很多内容。如果我错过了什么@Emil,请告诉我

以上是关于Flutter:类型 'Future<dynamic>' 不是类型 'Widget' 的子类型 // MaterialPageRoute<dynamic>(null))的主要内容,如果未能解决你的问题,请参考以下文章

类型 'Future<dynamic>' 不是 Flutter 数据库创建中的“Future<int>”类型异常的子类型

Flutter'Future<void>'不是'Widget'类型的子类型[重复]

参数类型“Future<bool>”不能分配给参数类型“Widget”[Flutter]

Flutter:类型 'Future<dynamic>' 不是类型 'Widget' 的子类型 // MaterialPageRoute<dynamic>(null))

如何修复 Flutter 中的“参数类型 'Future<int>' 无法分配给参数类型 'int'”

Flutter:“Future<dynamic>”不是“String”类型的子类型