Skip to main content

States

All StatefulWidget has two classes:

class Home extends StatefulWidget {
const Home({super.key});


State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: const SafeArea(
child: Center(
child: Text('Hello Body'),
),
),
);
}
}

The first part lines 1 to 6 are not to be changed. The second class is where we make changes.


Example App:

class Home extends StatefulWidget {
const Home({super.key});


State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
int x = 0; // declarinag variable which will change with buttons


Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: Column(
children: [
const SizedBox(height: 50),
Center(
child: Text('The count is $x'),
),
const SizedBox(height: 80),
Row(
children: [
ElevatedButton(
onPressed: () {
/// onPressed: (){ setState((){ ..statements..}) }
/// the onPress MUST have setState inside it
/// setState((){..}) conatains the statements which change the varaiable 'x' as button is pressed
setState(() {
--x;
});
},
child: const Text('Subtract'),
),
ElevatedButton(
onPressed: () {
setState(() {
++x;
});
},
child: const Text(' ADD '),
)
],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
x++;
});
},
backgroundColor: Colors.red,
child: Icon(Icons.add),
),
);
}
}

setState( () {} );

/// its written this way

setState( () {
/* Statements here like i++; ..... */
});

using with onPressed(){ .. },

      onPressed: () {
/// onPressed: (){ setState((){ ..statements..}) }
/// the onPress MUST have setState inside it
/// setState((){..}) conatains the statements which change the varaiable 'x' as button press
setState(() {
--x;
});
},