Flutter:生命周期状态:已创建,没有小部件,未安装

Flutter : lifecycle state: created, no widget, not mounted

如何解决此错误,以更新复选框选择状态。 更新SDK后出现问题

CheckBoxState#4712e(lifecycle state: created, no widget, not mounted)

请检查代码:

    class CheckBoxSampleExample extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Grid View Example'),
            ),
            body: CheckBoxExample(),
          ),
        );
      }
    }
    
    class CheckBoxExample extends StatefulWidget {
    
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        throw CheckBoxState();
      }
    }
    
    class CheckBoxState extends State<CheckBoxExample> {
    
      bool isChecked = false;
      
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Checkbox(value: isChecked,
            onChanged: (bool? value) {
                  setState(() {
                    isChecked = true;
                  });
            });
      }
    }
import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: CheckBoxSampleExample()));

class CheckBoxSampleExample extends StatelessWidget {
  const CheckBoxSampleExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Grid View Example'),
      ),
      body: const CheckBoxExample(),
    );
  }
}

class CheckBoxExample extends StatefulWidget {
  const CheckBoxExample({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CheckBoxState();
    //You missed initialization part of state object.
  }
}

class _CheckBoxState extends State<CheckBoxExample> {
  bool isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Checkbox(
        value: isChecked,
        onChanged: (bool? value) {
          setState(() {
            isChecked = isChecked ? false : true;
            //Inversing the boolean value
          });
        });
  }
}

看看这个。

  • 您还没有初始化状态对象。
  • 并且布尔值在状态变化中不反转。

我在代码中添加了注释请看