'secondhalf is not been initialized

enter image description here

some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.why get me this error

class _ExpendedTextState extends State<ExpendedText> {
  late String firstHalf;
  late String secondHalf;
  bool hiddenText = true;
  double textHeight = Dimentions.screenHeight / 5.63;

  @override
  void initState() {
    super.initState();
    if (widget.text.length > textHeight) {
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }
  }

  @override
  Widget build(BuildContext context) {
    return secondHalf.isEmpty
        ? SmallText(text: firstHalf)
        : Column(
            children: [
              hiddenText
                  ? SmallText(
                      text: firstHalf + "....",
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6,
                    )
                  : SmallText(
                      text: firstHalf + secondHalf,
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6),
              InkWell(
                onTap: () {
                  setState(() {
                    hiddenText = !hiddenText;
                  });
                },
                child: Row(
                  children: [
                    SmallText(
                      text: 'Show more',
                      color: AppColors.mainColor,
                    ),
                    Icon(
                      hiddenText ? Icons.arrow_drop_down : Icons.arrow_drop_up,
                      color: AppColors.mainColor,
                    ),
                  ],
                ),
              )
            ],
          );
  }
}


Solution 1:[1]

This error occurs when you try to access a late variable that hasn't been initialized yet.

In your case, you need to check and debug

    if (widget.text.length > textHeight) { ///if amount of characters is greater than screenheight / 5.63 . This sounds like a very rare case.
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }

So lets say you have a screenheight of 563. You'd need a text with 101 characters in order to initialize your late variables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christian