'calling state function from other state

I have an IndexedStack with BottomNavigationBar. The indexes stack has serveral widgets children, each is a stateful widget.

I want that pressing a button on on of the subwidget will change the active index of the IndexedStack (which I'm doing by using state manager) and will invoke a function of that new active widget state (I also need to pass parameters to it).

Are there any best practices to solve this? Any experience with similar problems?

Thanks.



Solution 1:[1]

Maybe you only pass callback function to child widget and call it on some event, something like this:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ParentWidget(),
    );
  }
}

class ParentWidget extends StatefulWidget {

  const ParentWidget();

  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(children: [
          ChildWidget(_incrementCounter),
          Text(_counter.toString()),
        ])
      )
    );
  }
}

class ChildWidget extends StatefulWidget {
  final Function callbackFunction;
  
  const ChildWidget(this.callbackFunction);
  @override
  _ChildWidgetState createState() => _ChildWidgetState();
  
}

class _ChildWidgetState extends State<ChildWidget> {
  
   @override
  Widget build(BuildContext context) {
    return ElevatedButton(child: const Text('call callback'), onPressed: () => widget.callbackFunction());
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ante Bule