简体   繁体   中英

Changing an attribute in a parent widget from a child widget

I am trying to create an app. I want to change an attribute in a parent class (so it can display a Visibility item, SlidingUpPanel) after submitting a query in the child class (which is a search bar).

I have tried using a callback function and followed How can I pass the callback to another StatefulWidget? but it doesn't seem to do anything when I submit my query in the search bar. Previously, I have also tried to use Navigator.push to call SlidingUpPanel directly but it resulted in a black screen with only SlidingUpPanel.

Parent class (Map):

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

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

class _MapPageState extends State<MapPage> {

  bool IsVisible = false;

  void callbackFunction() {
    setState(() {
      IsVisible = true;
    });
  }
  ...
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Stack(
          children: [
              ...
            Visibility(
                visible: IsVisible,
                child: SlidingUpPanel()),
            SearchPage(callbackFunction),
      ]),
    );
  }
}

Child class (Search Bar):

class SearchPage extends StatefulWidget {
  final Function callback;
  SearchPage(this.callback);
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  ...

  @override
  Widget build(BuildContext context) {
    return FloatingSearchBar(
        
        ...
            
        onSubmitted: (query) {
          // callback here, but doesn't seem to do anything
          widget.callback;
          controller.close();
        },

        ...
     );
   }
}

To actually call a function (execute it) you must use () .

Try calling the callback function like this:

onSubmitted: (query) {
  // use () to actually call the function
  widget.callback();
  controller.close();
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM