calling setState from drawer?

Issue

Context

Using the standard flutter demo I added a drawer. I put the contents of my drawer in another class in another file. Both are stateful widgets. I use a floating action button in the drawer with setState incrementing the global variable for the number shown on the main screen.

What happens

When I press it nothing happens.

It does not update the text on the main page/main.dart until I use the floating action button on the main page/main.dart. Then it adds all the increments I added in the drawer too.

So it’s just not rebuilding the widget.

How do I get it to rebuild the widget? I thought everything you needed was that they were both inside a setstate?

Best possible cause I have come up with

Is it because even though I use a stateful widget inside a stateful widget, the setstate only works on the embedded stateful widget because the embedded widget is technically a created object in the main.dart?

Code for main.dart

import 'package:flutter/material.dart';
import 'drawer.dart';

DrawerClass _drawer = DrawerClass();

int counter = 0;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  void _incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      endDrawer: SafeArea(child: Drawer(child: Container(child: _drawer,),)),
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Code for drawer

import 'package:flutter/material.dart';
import 'main.dart';

class DrawerClass extends StatefulWidget {
  @override
  _DrawerClassState createState() => _DrawerClassState();
}

class _DrawerClassState extends State<DrawerClass> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF222831),
      body: Container(
        width: 100,
        child: Center(
          child: FloatingActionButton(
            tooltip: 'Increment',
            child: Icon(Icons.add),
            onPressed: () {
              setState(() {
                counter++;
              });
            },
          ),
        ),
      ),
    );
  }
}

Solution

Just pass the _incrementCounter to the DrawerClass. With this change your DrawerClass can now be a StatelessWidget and there will be no need for the counter and _drawer variables to be global. Please see the code below :

main.dart

import 'package:flutter/material.dart';
import 'drawer.dart';

//DrawerClass _drawer = DrawerClass();

//int counter = 0;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int counter = 0;
  void _incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    final DrawerClass _drawer = DrawerClass(
      increment: _incrementCounter,
    );
    return Scaffold(
      endDrawer: SafeArea(
          child: Drawer(
        child: Container(
          child: _drawer,
        ),
      )),
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

drawer.dart

import 'package:flutter/material.dart';

class DrawerClass extends StatelessWidget {
  final Function increment;

  const DrawerClass({Key key, this.increment}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF222831),
      body: Container(
        width: 100,
        child: Center(
          child: FloatingActionButton(
            tooltip: 'Increment',
            child: Icon(Icons.add),
            onPressed: increment,
          ),
        ),
      ),
    );
  }
}

Answered By – bluenile

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.