Unable to work with Flutter Stateful widget

Issue

I’m Ravi. I am pretty much new to Flutter but I am not new to programming. I am Stuck working with stateful widgets of Flutter. Since i am new to this SDK i am unable to figure out why my state isn’t getting updated. What i did was just wrote some code that would increment a number whenever a button is clicked, And i knew that we have to use stateful widgets in order to update any data in realtime. but my code isn’t working as it has to. Can anyone help me with this.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
int level = 0;
return MaterialApp(
  home: Scaffold(
      appBar: AppBar(
        title: Text('Stateful Widget'),
      ),
      body: Center(
        child: Column(
          children: [
            Text('$level'),
            RaisedButton(
              child: Text('Increment'),
              onPressed: () {
                setState(() {
                  level = level + 1;
                  print(level);
                });
              },
            ),
          ],
        ),
      )),
);
}
}

Console: 
Performing hot reload...
Syncing files to device sdk gphone x86 arm...
Reloaded 1 of 513 libraries in 1,722ms.
I/flutter ( 8886): 1

Flutter Stateful widget demo

Solution

The problem is with the scope of your level variable. It shouldn’t be in your build method but in your class

class _MyAppState extends State<MyApp> {
//Moved level here.
  int level = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stateful Widget'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('$level'),
              RaisedButton(
                child: Text('Increment'),
                onPressed: () {
                  setState(() {
                    level = level + 1;
                    print(level);
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Answered By – Josteve

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.