title: Flutter - How to Extract Widget with onPressed setState inside?
body: <p>I want to Extract a Widget with <code>onPressed</code> <code>setState</code> inside but I get the Message &quot;<em>Reference to an enclosing class method cannot be extracted.</em>&quot;
  Is there a way to do that?</p>
  <p>I would like to divide my code into different widgets so that it remains clear. Here is simplified an example of the code:</p>
  <pre><code>import 'package:flutter/material.dart';
  
  void main() {
    runApp(MyApp());
  }
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Calculator(),
      );
    }
  }
  
  class Calculator extends StatefulWidget {
    @override
    _CalculatorState createState() =&gt; _CalculatorState();
  }
  
  class _CalculatorState extends State&lt;Calculator&gt; {
    var myValue = 0;
  
    void calculate() {
      myValue = 12;
    }
  
    @override
    Widget build(BuildContext context) {
      return Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              child: TextButton(
                onPressed: () {
                  setState(() {
                    calculate();
                  });
                },
                child: Text(
                  'Button 001',
                ),
              ),
            ),
            TextOutput(myValue: myValue),
          ],
        ),
      );
    }
  }
  
  class TextOutput extends StatelessWidget {
    const TextOutput({
      Key key,
      @required this.myValue,
    }) : super(key: key);
  
    final int myValue;
  
    @override
    Widget build(BuildContext context) {
      return Container(
        child: Text(
          myValue.toString(),
        ),
      );
    }
  }
  </code></pre>
  <p>The part I want to extract into a separate widget:</p>
  <pre><code>  Container(
      child: TextButton(
        onPressed: () {
          setState(() {
            calculate();
          });
        },
        child: Text(
          'Button 001',
        ),
      ),
    ),
  </code></pre>