I'm trying to learn flutter but his has been in my way for over a week, I'm not able to get setState to work properly.

In this case I want to press a button and change its icon and properties, basically having another element but I just can't get it to work.

Here's my code for the widget:

import 'package:flutter/material.dart';

class UserButton extends StatefulWidget {
  @override
  _UserButtonState createState() => _UserButtonState();
}

class _UserButtonState extends State<UserButton> {
  @override
  Widget build(BuildContext context) {
    bool loggedin = false;
    return Container(
        child: loggedin
            ? IconButton(
                onPressed: () {
                  setState(() {
                    loggedin = false;
                  });
                },
                icon: Icon(Icons.person),
              )
            : IconButton(
                onPressed: () {
                  setState(() {
                    loggedin = true;
                  });
                },
                icon: Icon(Icons.person_outline),
                tooltip: "Login",
              ));
  }
}

And here is the main app code:

import 'package:flutter/material.dart';

import 'package:orar/user_button.dart';

main(List<String> args) {
  runApp(Home());
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme:
          ThemeData(primaryColor: Colors.cyan, accentColor: Colors.cyanAccent),
      home: Scaffold(
        appBar: AppBar(
          title: Text("test"),
          actions: <Widget>[UserButton()],
        ),
        body: ListView(
          children: <Widget>[],
        ),
      ),
    );
  }
}


Solution 1: Dinesh Balasubramanian

loggedin should be state variable. In your case it is local variable inside build method.

Move loggedin out of build method and it should work