Home > OS >  Incorrect use of ParentDataWidget. Caused by not final variable in StatefulWidget
Incorrect use of ParentDataWidget. Caused by not final variable in StatefulWidget

Time:11-30

I'm new to flutter and I'm trying to make a widget which changes its text when you press it. I can't make the couter variable final because it can be changed in the setState methode. But because "a class that [my] class inherits from" is marked as @immutable (the StatefulWidget I suppose), I always get an "Incorrect use of ParentDataWidget" exception.

Is there a solution to this problem or is there a better way to implement such a widget.

Here is my code:

class TopInfoBanner extends StatefulWidget {
  int counter = 0;
  TopInfoBanner({Key? key}) : super(key: key);

  @override
  State<TopInfoBanner> createState() => _TopInfoBannerState();
}

class _TopInfoBannerState extends State<TopInfoBanner> {
  final Color textColor = cSecondaryColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 42.0,
      color: cBoxColor,
      child: Expanded(
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 2.0),
          child: InkWell(
            onTap: () {
              setState(
                () {
                  widget.counter  ;
                },
              );
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                if (widget.counter % 3 == 0)
                  infoBuilder('text 1', Icons.update_sharp),
                if (widget.counter % 3 == 1)
                  infoBuilder(
                      'text 2', Icons.ac_unit_sharp),
                if (widget.counter % 3 == 2)
                  infoBuilder('text 3',
                      Icons.gpp_good_outlined),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Padding infoBuilder(String text, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(
            icon,
            color: textColor,
          ),
          Text(
            text,
            style: Theme.of(context)
                .textTheme
                .bodyText1!
                .copyWith(color: textColor),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

Expanded widget is for the Row and Column.

  • Related