Home > other >  How do I make setState run from Class ? flutter
How do I make setState run from Class ? flutter

Time:02-18

I need to use a command in class other Example

I need to use a command in class other Example

import 'package:flutter/material.dart';
class SelectionUser {

  BuildContext _context;
  var _pagy;

  int n = 0;


  open(int x) {
    n = x * 10;
    setState(() {}); //////////////////////////////
  }


  SelectionUser(this._context, this._pagy);
}

CodePudding user response:

You can pass a VoidCallback parameter to your class like this:

import 'package:flutter/material.dart';

class Example extends State<...>{

  @override
  void initState(){
    super.initState();
    final user = SelectionUser(() => setState((){}), null)
  }

  ...
}


class SelectionUser {
  SelectionUser(this._setState, this._pagy);
  var _pagy;
  VoidCallback _setState;

  int n = 0;


  open(int x) {
    n = x * 10;
    _setState(); //////////////////////////////
  }
}

Then your user.open() will call the _setState callback that triggers the setState as required

CodePudding user response:

The fact that you need a BuildContext in your class and you want to call setState makes it obvious that you should not have a simple class, but instead inherit from StatefulWidget and State<>.

More information on how to do so can be found in the documentation.

  • Related