Home > Mobile >  setState Not Update StateFul Widget
setState Not Update StateFul Widget

Time:04-19

I have problem with my code. I am trying to update child by set a function of setState to the parent then fired it from stateless widget once button clicked. It gonna looks like

Main (Stateful) -> Parent (Stateless) [There we fire the setState when TextField input changed] -> Child (Stateful)

Here is the code

Function stateGoldTotalBox = (){}; //storing the setState function here
class BuildGoldTotalBox extends StatefulWidget {
  final String type;
  BuildGoldTotalBox({required this.type});

  @override
  State<BuildGoldTotalBox> createState() => _BuildGoldTotalBoxState();
}

class _BuildGoldTotalBoxState extends State<BuildGoldTotalBox> {
  int _amount = 0;
  Map language = globals.language;
  Future<bool> _updateState({required int amount}) async{
    if(this.mounted) {
      setState(() {
        _amount = amount;
        print('fired'); //this on is working fine
      });
    }
    return true;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    stateGoldTotalBox = _updateState;
  }

  @override
  Widget build(BuildContext context) {
    print(_amount); //this also working to check if setState working
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey,width: 0.5),
      ),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(language['total'].toString().toCapitalized()),
            Text(_amount.toStringAsFixed(2)), //THIS ONE DOES NOT CHANGE
            SvgPicture.asset('lib/assets/currency/money.svg',height: 20.0,),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

try use get plugin, https://pub.dev/packages/get you can update stateless widget with it

  • Related