Home > Software design >  Flutter: Widget notify when finish some task
Flutter: Widget notify when finish some task

Time:08-30

I have the following structure:

page_1.dart
text.dart

text.dart is a widget inside page_1.dart and it changes its text every X seconds and when it finishes it writes print('end') it works as expected.

But I'd like it to sends a signal for the page_1.dart when finished.

How would that be possible?

CodePudding user response:

You can use callback method from inner widget.


class Page1 extends StatefulWidget {
  const Page1({Key? key}) : super(key: key);

  @override
  State<Page1> createState() => _Page1State();
}

class _Page1State extends State<Page1> {
  int? data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          InnerTask(
            callback: (p0) {
              setState(() {
                data = p0;
              });
            },
          ),
          Text("parent widget got $data")
        ],
      ),
    );
  }
}


class InnerTask extends StatefulWidget {
  final Function(int) callback;

  const InnerTask({Key? key, required this.callback}) : super(key: key);

  @override
  State<InnerTask> createState() => _InnerTaskState();
}

class _InnerTaskState extends State<InnerTask> {
  int counter = 0;

  late Timer timer;

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        counter  ;
      });
      widget.callback(counter);
    });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text("data $counter");
  }
}

CodePudding user response:

You could use different forms of Flutter state managers. In your specific use case I would recommend use one of the most basics: Streams.

Streams allows notify events around the application.

  • Related