Flutter: Access variable declared and defined in _Widgetstatefulstate from Statefulwidget

56 Views Asked by At

I need to access a variable declared and defined in the state of my stateful widget:

class StatItemDeclarable extends StatefulWidget {
  const StatItemDeclarable({Key? key, required this.title, required this.index}) : super(key: key);

  final String title;
  final int index;
  
  //Need to access variables here


  @override
  State<StatItemDeclarable> createState() => _StatItemDeclarableState(title: title, index: index);
}

class _StatItemDeclarableState extends State<StatItemDeclarable> {

  _StatItemDeclarableState({required this.title, required this.index});

  String title; // Variable to access
  final _titleController = TextEditingController();
  final int index;
  bool deleted = false;
  late Color _color; // Variable to access

I'm quite new to flutter so I would appreciate some help :)

The variables I wanted to access were not accessable in the StatefulWidget

2

There are 2 best solutions below

1
On

you can access to these variables just by using widget. like this:

widget.title;
0
On

you can access any var declared in constructer by used keyword widget before variable name like this:

widget.title;
widget.index;