Home > Net >  StatefulWidget (setState not work did't show )
StatefulWidget (setState not work did't show )

Time:05-18

import 'package:flutter/material.dart';
class CounterScreen extends StatefulWidget
{
  const CounterScreen({Key? key}) : super(key: key);
  

  @override
  State<CounterScreen> createState() {
    
    return _CounterScreenState();
  }
}


class _CounterScreenState extends State<CounterScreen> {
int number=1;

   @override
  Widget build(BuildContext context) {
  
  return Scaffold(
    appBar: AppBar(
      title: Text(
        "Counter"
      ),
    ),
    body: Center(

      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,

        children: [

          TextButton(onPressed: (){ number--;} , child: Text("Minus",)),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            child: Text("$number",style: TextStyle(color: Colors.black,fontSize: 30,),),
          ),
          TextButton(onPressed: (){ number  ;print(number);}, child: Text("Plus",)),

        ],
      ),
    ),
  );
  }

}

CodePudding user response:

you have to use setstate where you want to update the UI. so this line should be

TextButton(onPressed: (){ number--;} , child: Text("Minus",)),

Like this

TextButton(
        onPressed: () {
          setState(() {
            number--;
          });
        },
        child: const Text(
          "Minus",
        ));
  • Related