简体   繁体   English

flutter 应用程序中的“setState() 或 MarkNeedsBuild() 调用期间”错误

[英]“setState() or MarkNeedsBuild() called during” error in flutter app

I am a beginner in flutter.我是 flutter 的初学者。 When I call Settings widget the following error occurs.当我调用Settings widget时,会发生以下错误。 I tried everyhing that has been posted from the same issue, but nothing changed.我尝试了从同一问题发布的所有内容,但没有任何改变。 When I remove the StreamBuilder it works fine.当我删除StreamBuilder时,它工作正常。 However, without the StreamBuilder I cannot get the data from cloud firestore and display it in the settings widget.但是,如果没有StreamBuilder ,我将无法从 cloud firestore 获取数据并将其显示在设置小部件中。

Here is Home screen where I call the Settings widget .这是我调用Settings widget的主屏幕。

body: FlatButton.icon(
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => Settings()));
            },
            icon: Icon(Icons.settings),
            label: Text('User Profile')),
      );

Here is Settings widget这是设置小部件

import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_firebase_test/screens/services/auth.dart';
import 'package:flutter_firebase_test/shared/loading.dart';

class Settings extends StatefulWidget {
  @override
  _Settings createState() => _Settings();
}

class _Settings extends State<Settings> {
  AuthService _auth = new AuthService();
  @override
  Widget build(BuildContext context) {
    Color randomColor() {
      int index = 0;
      List colors = [
        Colors.red,
        Colors.blue,
        Colors.green,
        Colors.yellow,
        Colors.amber,
        Colors.deepPurple
      ];
      Random rnd = new Random();
      setState(() => index = rnd.nextInt(6));
      return colors[index];
    }

    return StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection('users').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Loading();
          } else {
            return Scaffold(
              body: Container(
                padding: EdgeInsets.fromLTRB(30, 80, 30, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      child: Column(
                        children: [
                          CircleAvatar(
                            backgroundColor: randomColor(),
                            //backgroundImage: AssetImage('assets/avatars/male1.jpg'),
                            radius: 60,
                            child: Text(
                              // TODO: The name will be set later!
                              "Ali"[0].toUpperCase(),
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: 40,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          Text("dasdas"),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    Divider(
                      color: Colors.black,
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Wrap(children: [
                      Text(
                        "Name:",
                        style: TextStyle(
                          fontSize: 20,
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                    ]),
                    SizedBox(
                      height: 40,
                    ),
                    Wrap(children: [
                      Text(
                        "Username:",
                        style: TextStyle(
                          fontSize: 20,
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Text(
                        "User fullname will display here",
                        style: TextStyle(
                          fontSize: 20,
                        ),
                      ),
                    ]),
                  ],
                ),
              ),
            );
          }
        });
  }
}

flutter doctor -v result flutter doctor -v结果

] Flutter (Channel stable, 1.22.5, on Microsoft Windows [Version 10.0.19042.685], locale en-US)
    • Flutter version 1.22.5 at C:\src\flutter
    • Framework revision 7891006299 (3 weeks ago), 2020-12-10 11:54:40 -0800
    • Engine revision ae90085a84
    • Dart version 2.10.4       

 
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at C:\Users\demir\AppData\Local\Android\sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

Debug console:调试控制台:

The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#778da):
setState() or markNeedsBuild() called during build.
This Settings 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.

    state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#778da
The relevant error-causing widget was
StreamBuilder<QuerySnapshot>
package:flutter_firebase_test/…/home/settings.dart:31
When the exception was thrown, this was the stack
#0      Element.markNeedsBuild.<anonymous closure>
package:flutter/…/widgets/framework.dart:4292
#1      Element.markNeedsBuild
package:flutter/…/widgets/framework.dart:4307
#2      State.setState
package:flutter/…/widgets/framework.dart:1264
#3      _Settings.build.randomColor
package:flutter_firebase_test/…/home/settings.dart:27
#4      _Settings.build.<anonymous closure>
package:flutter_firebase_test/…/home/settings.dart:47
...


Put your randomColor method outside the build method.将您的randomColor方法放在build方法之外。 Also you don't need to call setState on your index variable since it's local in that method此外,您不需要在索引变量上调用setState ,因为它在该方法中是本地的

Color randomColor() {
  int index = 0;
  List colors = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.yellow,
    Colors.amber,
    Colors.deepPurple
  ];
  Random rnd = new Random();
  index = rnd.nextInt(6);
  return colors[index];
}

// ...

@override
Widget build(BuildContext context) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “在构建过程中调用了 setState() 或 markNeedsBuild()”如何解决这个问题? - "setState() or markNeedsBuild() called during build" how to resolve this? 在构建 TextField 期间调用 setState() 或 markNeedsBuild() - setState() or markNeedsBuild() called during build TextField Flutter:当小部件树被锁定时调用 setState() 或 markNeedsBuild() ... 在方向更改期间 - Flutter: setState() or markNeedsBuild() called when widget tree was locked... during orientation change (在构建过程中出现错误)在构建过程中调用了 setState() 或 markNeedsBuild()。相关的导致错误的小部件是 MaterialApp - (Getting the error while building) setState() or markNeedsBuild() called during build.The relevant error-causing widget was MaterialApp 无限滚动列表视图 - 在构建期间调用的setState()或markNeedsBuild - Infinite Scroll listview - setState() or markNeedsBuild called during build setState() 或 markNeedsBuild() 在构建期间调用。 在导航推送中 - setState() or markNeedsBuild() called during build. in Navigator Push 如何将函数从子类传递到父类,我收到此错误:在构建期间调用了 setState() 或 markNeedsBuild() - How to pass function from a child class to parent class, I am getting this error: setState() or markNeedsBuild() called during build 为什么 Flutter 中的 BloCListener 不保存状态,并且在身份验证过程中出现 setState() 问题? - Why is BloCListener in Flutter not saving state, and there's a setState() issue during authentication? setState 方法不会刷新我的 flutter 应用程序中的所有页面 - The setState method doesn't refresh all the page in my flutter app 该方法在 flutter 中的 null 错误上调用 - The method was called on null error in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM