草庐IT

checkbox - 在构造函数中调用 SetState()

coder 2023-07-23 原文

我已经建立了一个自定义列表。现在我包含一个复选框,如果我要选中或取消选中,则会抛出以下错误:'setState() 在构造函数中调用'

class Lists extends StatefulWidget{  
     @override
    _List createState() => _List();
}

class _List extends State<Lists> {  
  bool checkedvalue = true;
  @override
Widget build(BuildContext context) {

 return futureBuilder();
}

Widget futureBuilder(){  
  var futureBuilder = new FutureBuilder(
      future: rest.fetchPost(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return new Text('loading...');
          default:
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            else                    
                return listBuilder(context, snapshot);            
        }
      }
 );

 return new Scaffold(         
      body: futureBuilder,
    );
}

Widget listBuilder(BuildContext context, AsyncSnapshot snapshot) {  
  List<rest.Status> values = snapshot.data;

  if (values == null || values.length == 0){
    return null;
  }


  int items = values.length;

  return ListView.builder(   
  itemCount: items,
  itemBuilder: (BuildContext context, int index) {
    String statusText;
    Image image ;
    Uint8List bytes;

    if(statusList.globalStatus != null){
      for(int i=0;i< statusList.globalStatus.length; i++){
        if(values[index].statusID == statusList.globalStatus[i].id){

            if(statusList.globalStatus[i].kurzform != null){
              statusText = statusList.globalStatus[i].kurzform;
            }else{
              statusText = statusList.globalStatus[i].kurzform;
            }

            if (statusList.globalStatus[i].icon != null){
              bytes = base64Decode(statusList.globalStatus[i].icon);
              image = new Image.memory(bytes) ;
            } 
        }

        if(image== null || statusText == null){            
          statusText= 'Kein Status';
          image=  new Image.asset('assets/null.png');
        }              
      }
    }   
    return new Container( 
      decoration: new BoxDecoration(
          border: Border(top: BorderSide(
          color: Colors.black26,
          width: 1
          )
        )
      ), 


      child:Column(
        children: <Widget>[
          CustomListItemTwo( 
            statusText: statusText,                               
            status:image,
            materialNR: values[index].uArtText,          
            material: values[index].untersuchungsMaterialName,
            probenArt:  values[index].probenart,
            eingansdatum: values[index].eingangsdatumText,
            patient: values[index].vorname + ' ' + values[index].nachname ,
            geburtsdatum: values[index].geburtstagText ,

          ),
          Checkbox(            
              value: checkedvalue ,           
              onChanged: (bool newValue) =>                
                setState(() {
                  checkedvalue = newValue; 
                })              
            ),
        ] 
      ),
    );
  }       
  );
}

}

I/flutter(5067):══╡手势异常╞═══════════════════════════════ ═══════════════════════════════════ I/flutter ( 5067 ): 处理手势时抛出以下断言: I/flutter ( 5067): setState() 在构造函数中调用:_List#9044e(生命周期状态:已创建,无小部件,未安装) I/flutter ( 5067 ): 当你在状态对象上调用 setState() 用于尚未插入的小部件时,会发生这种情况 I/flutter ( 5067 ): widget 树还没有。不必在构造函数中调用 setState(),因为状态是 I/flutter ( 5067 ): 在最初创建时已经假设它是脏的。

最佳答案

我下面的代码不是testet。

您的代码中存在概念错误。您应该在构建方法中获取任何内容!

如果你把打印出来,例如在你的构建方法中“构建...”(正如我在下面所做的那样)你会明白为什么。构建方法的调用次数超出您的想象。因此,您多次调用 WebService 或其他任何东西,响应将不止一次。实际上 setState() 方法将触发构建。

如果你想在开始时拉一些东西,使用 initState() 方法。创建状态时将调用一次此方法。将变量用于调用状态并在构建方法中对其使用react(如前所述,setState() 将触发重建)。

考虑到这个概念,我稍微重构了你的代码,你的开关/复选框问题可能会消失。

另外请看一下如何使用Futures https://api.flutter.dev/flutter/dart-async/Future-class.html

class Lists extends StatefulWidget {
  @override
  _List createState() => _List();
}

class _List extends State<Lists> {
  bool checkedvalue = true;
  bool loading = true;
  AsyncSnapshot asyncSnapshot = null;

  @override
  void initState() {
    futureBuilder();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("building...");
    if(asyncSnapshot != null && asyncSnapshot.hasError){
      return Text("Error : ${asyncSnapshot.error}");
    }
    return (loading) ? Text("LOADING") : listBuilder(context, asyncSnapshot);
  }

  void futureBuilder() async {
    rest.fetchPost().then((snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
        case ConnectionState.waiting:
          setState(() {
            loading = true;
          });
          break;
        default:
          if (snapshot.hasError) {
            setState(() {
              loading = false;
            });
          } else {
            setState(() {
              loading = false;
              asyncSnapshot = snapshot;
            });
          }
      }
    });
  }
  .....

关于checkbox - 在构造函数中调用 SetState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807074/

有关checkbox - 在构造函数中调用 SetState()的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  3. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  4. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  5. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  8. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  9. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  10. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

随机推荐