0

I need to expose a couple of functions of a Stateful Widget. Since these functions depend on the state of the widget, I created a variable to store the state. However, I am getting a compile time warning:

This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final.

My Code:

class ItemWidget extends StatefulWidget {
  final Record record;
  final Function additem;
  final Function removeItem;
  var state;
  ItemWidget(this.record, this.additem, this.removeItem);

  @override
  _ItemWidgetState createState() {
    return this.state = new _ItemWidgetState();
  }

  // These are public functions which I need to expose.
  bool isValid() => state.validate();
  void validate() => state.validate();
}

Is there a better way /correct way of achieving this?

Thanks.

Tushar
  • 1,242
  • 1
  • 8
  • 19
  • what exactly you're trying to achieve? – OMi Shah Jan 18 '23 at 05:15
  • @Omishah I want to expose isValid to the outer world, so that they can check if item is valid. This widget is a part of the bigger form. The master screen, iterates over all the widgets and if all the widgets are valid, it proceeds further. – Tushar Jan 18 '23 at 06:15

1 Answers1

0

You should write the function on state, and access it via GlobalKey.

import 'package:flutter/material.dart';

class ItemWidget extends StatefulWidget {
  final Record record;
  final Function additem;
  final Function removeItem;
  const ItemWidget(
    Key? key,
    this.record,
    this.additem,
    this.removeItem,
  ) : super(key: key);

  @override
  ItemWidgetState createState() => ItemWidgetState();
}

class ItemWidgetState extends State<ItemWidget> {
  bool isValid() {
    return true;
  }

  void validate() {}

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

https://api.flutter.dev/flutter/widgets/GlobalKey-class.html

dangngocduc
  • 1,588
  • 8
  • 13
  • 'state' is not available in ItemWidgetState. Moreover, I want to expose isValid to the outer world, so that they can check if item is valid. This widget is a part of the bigger form. The master screen, iterates over all the widgets and if all the widgets are valid, it proceeds further. – Tushar Jan 18 '23 at 06:14
  • You will need write body for that func, that code is sample. I have updated code sample for you. – dangngocduc Jan 18 '23 at 06:46
  • But, the ItemWidgetState class is not will the end user accesses. They access ItemWidget. It doesn't have a Validate funtion. – Tushar Jan 19 '23 at 08:36