Saturday, April 24, 2021

Stateless and Stateful widgets

 when state changes during app running or user interactions happened, use stateful widget.

stful <enter>

stless <enter>


creates one more class with _<classname>State.

Here you paste the complete content from your old stateless widget.


update the state variables using setState method so that it will call build if any changes there.


import 'package:flutter/material.dart';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Text('Dicee'),
          backgroundColor: Colors.red,
        ),
        body: DicePage(),
      ),
    ),
  );
}

class DicePage extends StatefulWidget {
  @override
  _DicePageState createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  int leftDiceNumber = 1;
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        children: <Widget>[
          Expanded(
            //flex: 4,
            child: FlatButton(
              onPressed:(){//void callback and anonymous function
                print('Left button got pressed');
                setState(() {
                  leftDiceNumber=5;
                });

              } ,
              child: Image(
                //width: 200.0,

                image: AssetImage('images/dice$leftDiceNumber.png'),
              ),
            ),
          ),
          Expanded(
            //flex: 2,
            child: FlatButton(
              onPressed:()=>print("right button clicked"),
              child: Image.asset(
                'images/dice1.png',
              ),
            ),
          ),
        ],
      ),
    );
  }
}

No comments:

Post a Comment