Flutter:调整小部件大小后出现LateInitializationError

yxyvkwin  于 2023-06-07  发布在  Flutter
关注(0)|答案(2)|浏览(163)

在调整小部件大小后,我在items_head上得到一个LateInitializationError
这是代码:

class Head_View extends StatefulWidget {
  Head_View({Key? key}) : super(key: key);
  late List<AppointmentItemWrapper> items_head;
  //late MultiChildRenderObjectWidget DTIT_head; --> **EDIT ON 20230605**
  @override
  State<Head_View> createState() => _Head_ViewState();
}

class _Head_ViewState extends State<Head_View> {
  @override
  void initState() {

    widget.items_head = [
      AppointmentItemWrapper(
        ID: 111,
        key: UniqueKey(),
        startDateTime: DateTime(2022, 1, 1, 8, 00, 0),
        endDateTime: DateTime(2022, 1, 1, 9, 30,0),
        position: 0,
        text: "Event N1",
        positiondragging: (double valxx) { print("HAHAH"); },
      ),
    ];

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return DynamicTimeline(
      key: _myWidgetKey_DTIT_head,
      firstDateTime: DateTime(2022, 1, 1,7,0,0),
      lastDateTime: DateTime(2022, 1, 1,18,0,0),
      labelBuilder: DateFormat('hh:mm').format,
      items: widget.items_head, );
  }
}

就像我想的:
initState()通常应该只在第一次构建之前调用(第一次构建将发生在super.init()中?))并且当调整小部件的大小时,应该再次调用build来重建小部件,但是items_head应该已经在范围内了,或者我错了吗?

ivqmmu1c

ivqmmu1c1#

当使用有状态小部件类型时,您应该初始化状态小部件中的变量。
将下面的items_head移动到state小部件。

class Head_View extends StatefulWidget {
  Head_View({Key? key}) : super(key: key);
  @override
  State<Head_View> createState() => _Head_ViewState();
}

class _Head_ViewState extends State<Head_View> {
  
  late List<AppointmentItemWrapper> items_head;

@override
  void initState() {

    items_head = [
      AppointmentItemWrapper(
        ID: 111,
        key: UniqueKey(),
        startDateTime: DateTime(2022, 1, 1, 8, 00, 0),
        endDateTime: DateTime(2022, 1, 1, 9, 30,0),
        position: 0,
        text: "Event N1",
        positiondragging: (double valxx) { print("HAHAH"); },
      ),
    ];

    super.initState();
  }

....
9jyewag0

9jyewag02#

如果在class Head_View extends StatefulWidget {中声明items_head
它将在每次重建时清空列表。
试着在这里声明。

class _Head_ViewState extends State<Head_View> {

  late List<AppointmentItemWrapper> items_head;// **in here**

  @override
  void initState() {

    widget.items_head = [
      AppointmentItemWrapper(
        ID: 111,
        key: UniqueKey(),
        startDateTime: DateTime(2022, 1, 1, 8, 00, 0),
        endDateTime: DateTime(2022, 1, 1, 9, 30,0),
        position: 0,
        text: "Event N1",
        positiondragging: (double valxx) { print("HAHAH"); },
      ),
    ];

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return DynamicTimeline(
      key: _myWidgetKey_DTIT_head,
      firstDateTime: DateTime(2022, 1, 1,7,0,0),
      lastDateTime: DateTime(2022, 1, 1,18,0,0),
      labelBuilder: DateFormat('hh:mm').format,
      items: widget.items_head, );
  }
}

相关问题