Search code examples
flutterdartflutter-testflutter-statestatefulwidget

My screen doesn't reflect the changes in my app though the setState method works well


I'm trying to call a StatefulWidget(i.e FirstPage()) within a MaterialApp. I'm pretty much new to flutter and I don't know where I went wrong. According to my knownledge I've used StatefulWidget to tell flutter my screen on that page is going to encounter some changes in UI. But I got no idea to fix this error.


main.dart file:


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

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
        debugShowCheckedModeBanner: false,
        home: FirstPage());
  }
}

class FirstPage extends StatefulWidget {
  const FirstPage({Key? key}) : super(key: key);

  @override
  State<FirstPage> createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  @override
  Widget build(BuildContext context) {
    String buttonName = "Click";
    int currentIndex = 0;
    return Scaffold(
      appBar: AppBar(
        title: const Text("App title "),
      ),
      body: Center(
        child: currentIndex == 0
            ? Container(
                width: double.infinity,
                height: double.infinity,
                color: Colors.blueAccent,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 280,
                      height: 80,
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(
                            side: BorderSide.none,
                            borderRadius: BorderRadius.circular(18),
                          ),
                          backgroundColor: const Color.fromRGBO(9, 8, 99, 90),
                          foregroundColor: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            buttonName = "Clicked";
                            //print(buttonName0);
                          });
                        },
                        child: Text(buttonName),
                      ),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (BuildContext context) {
                              //'BuildContext' - datatype and 'context' - variable name
                              return const SecondPage();
                            },
                          ),
                        );
                      },
                      child: const Text("Move to new page"),
                    ),
                  ],
                ),
              )
            : Image.asset("images/img.png"),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(label: "Home", icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: "Settings", icon: Icon(Icons.settings))
        ],
        currentIndex: currentIndex,
        onTap: (int index) {
          //index value here is returned by flutter by the function 'onTap'
          setState(() {
            currentIndex = index;
            //print(currentIndex);
          });
        },
      ),
    ); //Scaffold represents the skeleton of the app(displays white page)
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

Images:

Before pressing Click and Settings button

After pressing Click and Settings looks the same

I want the screen to change the ElevatedButton Click to Clicked when onPressed() is triggered and also, the app should be able to switch settings page when the onTap() method is triggered in the bottom navigation bar.

The code worked initially when I refrained from calling an entire page of Scaffold from Material app, but as soon as I changed the part


class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
        debugShowCheckedModeBanner: false,
        home: FirstPage());     //<-- this part
  }
}

I'm getting this error.


Solution

  • Put your variables outside the build method.Else it will reset to default on every build. It will be like

    class _FirstPageState extends State<FirstPage> {
        //here 
        String buttonName = "Click";
        int currentIndex = 0;
    
      @override
      Widget build(BuildContext context) {
        // Not here
        return Scaffold(
          appBar: AppBar(
    

    More about StatefulWidget