2

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

1 Answer 1

3

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);
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

exactly, because when you call the method setState() it calls the build() method so the level variable is set back to 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.