当我将小部件添加到Listview时,出现错误

时间:2020-01-29 03:07:16

标签: flutter dart

错误是

在构造函数中调用的

setState():_journalItemState#76cf3(生命周期状态:已创建,未安装小部件,未安装)当您在State对象上为尚未插入小部件树的小部件调用setState()时,会发生这种情况然而。不必在构造函数中调用setState(),因为在最初创建状态时就已经假定该状态为脏状态。

如果在将数据插入到列表后不调用setState不会导致错误,但是在那种情况下将不会显示数据。 这是我的代码。


import '../Userdata.dart';
import '../normalhttp.dart';
import '../thirdparty/alert.dart';
import 'journalItem.dart';
import 'package:flutter/material.dart';
import 'package:Lifer_flutter/normalhttp.dart';

class journalList extends StatefulWidget {
  String jwt;
  String userName;
  journalList (this.jwt,this.userName,{Key key}) :super (key:key);
  @override
  State<StatefulWidget> createState() {
    return new RJournalList ();
  }
}
class RJournalList extends State<journalList> {
  LiferLocalizations locale;
  List<String> ids;
  final ScrollController _scrollController = ScrollController ();
  int journalReadBegin = 0;
  int oneTimeLoadJournalItemNumber = 10;
  Future<Null> refreshAll () async{
    ids.clear();
    journalReadBegin = 0;
    //return null;
    await insertSeveralJournals();
    return null;
  }
  Future <void> insertSeveralJournals () async{
    Map<String,dynamic> ret = await JsonPost ("/JournalSystem/GetLeastSeveralJournals", {
      "jwt":widget.jwt,
      "ItemNumberStart":journalReadBegin,
      "ItemNumberEnd":journalReadBegin + oneTimeLoadJournalItemNumber,
    });
    if (!ret.containsKey("result") || ret ["result"] == false) {
      networkErrorAlert(context);
      return ;
    }
    List<String> rids = List.from(ret ["payload"]);
    debugPrint ("l:" + rids.length.toString());
    setState(() {
      ids = rids;
    });
    // for (int i = 0;i < rids.length;++ i) {
    //     ids.add (rids [i]);
    //   }
  }
  bool loaded = false;
  @override
  Widget build(BuildContext context) {
    locale = LiferLocalizations.of (context);
    if (!loaded) {
      ids= List ();
      loaded = true;
    }
    CheckJwt().then((res) {
      if (!res) {
        networkErrorAlert(context);
        Navigator.pop(context);
      }
    });
    GetOneTimeLoadJournalItemNumber ().then((num) {
      oneTimeLoadJournalItemNumber = num;
    });
    return Scaffold(
      appBar: AppBar (
        title: new Text (locale.yourJournal),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
                //foregroundColor: Colors.white,
                backgroundColor: Colors.amber,
                shape: const CircleBorder(),
                onPressed: () async {
                  Map<String,dynamic> ret = await JsonPost ("/JournalSystem/NewJournal",{
                      "jwt":widget.jwt
                    }
                  );
                  if (ret.containsKey("result") == false) {
                    networkErrorAlert(context);
                    return ;
                  }
                  refreshAll();
        },
      ),
      body:  RefreshIndicator(
          onRefresh: refreshAll,
          child:
            new ListView.builder(
              itemCount: ids.length,
              itemBuilder: (context,index) {
                debugPrint (ids [index]);
                //return journalItem (widget.jwt,ids [index]);
                debugPrint ("added");
                return journalItem (
                  journalId: ids [index],
                  jwt: widget.jwt,
                  key: GlobalKey ()
                );
              },
              physics: new AlwaysScrollableScrollPhysics(),
              controller: _scrollController, 
            ),
      )
    );
  }
}

当我调用insertSeveralJournals时出现错误。 journalItem的代码。

import 'package:Lifer_flutter/thirdparty/MaterialTapWidget.dart';
import 'package:flutter/material.dart'; 
import 'package:Lifer_flutter/journal/struct.dart';
import 'journalShow.dart';
class journalItem extends StatefulWidget {
  String jwt,journalId;
  journalItem ({this.jwt,this.journalId,Key key}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    return _journalItemState (jwt,journalId);
  }
}
class _journalItemState extends State <journalItem> {
  IconData data;
  String journalId,jwt;
  Weather iconId;
  Journal journal;
  _journalItemState (this.jwt,this.journalId) {
    setState ((){
      journal = Journal (context,journalId,jwt,() {
        iconId = journal.weatherIcon;
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return 
  MaterialTapWidget (
    onTap: () {
      //点击那就进入展示页面。
      MaterialJournalShowWindow (journal);
    },
    child:Padding (
      padding: const EdgeInsets.all(20.0),
      child: Row(
        children: <Widget>[
          Icon (getIconData(iconId)),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text (
                journal.title,
                style: TextStyle(
                  fontSize: 50,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              Text (
                journal.content,
                softWrap: true,
                maxLines: 4,
                overflow: TextOverflow.ellipsis,
              )
            ],
          )
        ],
      ),
    )
  );
  }
}

调试日志。

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
[38;5;244mThe following assertion was thrown building NotificationListener<KeepAliveNotification>:[39;49m
setState() called in constructor: _journalItemState#76cf3(lifecycle state: created, no widget, not mounted)


[38;5;248mThis happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.[39;49m

[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0      State.setState.<anonymous closure>[39;49m
[38;5;244m#1      State.setState[39;49m
[38;5;248m#2      new _journalItemState[39;49m
[38;5;248m#3      journalItem.createState[39;49m
[38;5;244m#4      new StatefulElement[39;49m
[38;5;244m...[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 263 pos 16: 'child == null || indexOf(child) > index': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
A RenderSliverPadding expected a child of type RenderSliver but received a child of type RenderErrorBox.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mListView[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mRefreshIndicator[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mRefreshIndicator[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mRefreshIndicator[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mScaffold[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mjournalList[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4022 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.
[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mjournalList[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
Duplicate GlobalKey detected in widget tree.
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

2 个答案:

答案 0 :(得分:0)

请勿在该setState的构造函数中调用State。随便

_journalItemState (this.jwt,this.journalId) {
  journal = Journal (context,journalId,jwt,() {
    iconId = journal.weatherIcon;
  });
}

答案 1 :(得分:0)

在您的错误日志响应中,该响应非常清楚。

不必在构造函数中调用setState(),因为在最初创建状态时就已经假定该状态为脏状态。

旨在创建构造函数,只是为了保存对象,传递数据而不处理功能或更改UI的行为。在构造函数内部添加setState()完全是一种不好的方法。