Search code examples
flutterstatesetstate

How to do operations on state constructor variables in Flutter?


I'd like to show change of wordCount in homeWidget

    return Scaffold(
      body: Column(
        children: [
          ...
          Expanded(
            flex: 1,
            child: RecorderView(
              onSaved: _onRecordComplete,
              wordCount:wordCount,
            ),
          ),
        ],
      ),
    );

the variablewordCount relies on RecordView method:

I write this to get state variable here

class RecorderView extends StatefulWidget {
  final Function onSaved;
  final int wordCount;
  const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
  @override
  _RecorderViewState createState() => _RecorderViewState();
}

class _RecorderViewState extends State<RecorderView> {

//in one method
    widget.wordCount++;
}

I want to add wordCount here,but it says it's a final one.How could I inherit wordCount from homeWidget without final? I just want to change the word show in wordCount automatically,thanks!!


Solution

  • You cant inherit the variable, you can however initialize it to a value from the widget.

    class RecorderView extends StatefulWidget {
      final Function onSaved;
      final int wordCount;
      const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
      @override
      _RecorderViewState createState() => _RecorderViewState();
    }
    
    class _RecorderViewState extends State<RecorderView> {
    int _wordCount;
    
    @override
    void initState() {
    super.initState();
    _wordCount = widget.wordCount;
    }
    }