Controlling State from outside of a StatefulWidget

前端 未结 7 1034
耶瑟儿~
耶瑟儿~ 2020-11-29 18:44

I\'m trying to understand the best practice for controlling a StatefulWidget\'s state outside of that Widgets State.

I have the following interface defined.

<
7条回答
  •  情深已故
    2020-11-29 19:05

    You can use eventify

    This library provide mechanism to register for event notifications with emitter or publisher and get notified in the event of an event.

    You can do something like:

    // Import the library
    import 'package:eventify/eventify.dart';
    final EventEmitter emitter = new EventEmitter();
    
    var controlNumber = 50;
    
    List buttonsGenerator() {
        final List buttons = new List();
        for (var i = 0; i < controlNumber; i++) {
            widgets.add(new MaterialButton(
                      // Generate 10 Buttons afterwards
                      onPressed: () {
                        controlNumber = 10;
                        emitter.emit("updateButtonsList", null, "");
                      },
                    );
        }
    }
    
    class AState extends State {
        @override
        Widget build(BuildContext context) {
            List buttons_list = buttonsGenerator();
            emitter.on('updateButtonsList', null, (event, event_context) {
                setState(() {
                    buttons_list = buttonsGenerator();
                });
            });
        }
        ...
    }
    

    I can't think of anything which can't be achieved by event driven programming. You are limitless!

    "Freedom cannot be bestowed — it must be achieved." - Elbert Hubbard

提交回复
热议问题