mjr
mjr

Reputation: 97

Widget state updated by scaffold floatingActionButton

I have a scaffold which includes a floatingActionButton as demonstrated below:

return new Scaffold(
        appBar: new AppBar(
            title : new Text('Test Flutter'),
        ),
        body: new Center(
            child: new ListSection(),
        ),
        floatingActionButton: new FloatingActionButton(
            child: new Icon(Icons.add),
            onPressed: null
        ),
    );

List section:

class ListSection extends StatelessWidget
{
    @override
    Widget build(BuildContext context) {
        return new Container(
            child: new Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                    new WeekSection(),
//                  new MonthSection(),
//                  new YearSection()
                ]
            )
        );
    }
}

Lastly WeekSection is defined as follow:

class WeekSection extends StatefulWidget
{
    @override
    _WeekSectionState createState() => new _WeekSectionState();
}

How would I go about using the floatingActionButton.onPressed to updated the sate in _WeekSectionState

Upvotes: 0

Views: 50

Answers (1)

Tree
Tree

Reputation: 31431

Basic way would be to have a private var in your MyApp where scaffold, and to pass the reference to that field all the way down to the WeekSection,

So you pass this variable trough constructor to the ListSection and pass it down again trough constructor to WeekSection.

inside WeekSectionState you can access it as widget.someField from WeekSection;

Later, when you call setState inside MyApp directly in the listener of the FloatingActionButton it will rebuild WeekSection because the Widget that holds information for the state has changed. The flutter checks all the children that need rebuilding.

Upvotes: 1

Related Questions