3

I have the main/homepage widget of my app, let's call it home.dart.

Inside this widget, I have defined the drawer key in my Scaffold widget. The code for the Drawer object is in a separate file, navdrawer.dart.

home.dart

import 'navdrawer.dart';
. . .
@override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavDrawer(),
      ...

Now inside NavDrawer, I construct my Drawer widget which has a settings button, which links to the settings.dart screen.

Which I do like this:

navdrawer.dart

. . .
InkWell(
              onTap: () async {
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Settings()),
                );
                print(result);
              },
              child: ListTile(
                  leading: Icon(
                    Icons.settings,
                    color: AppTextColor,
                  ),
                  title: Text('Settings'))),

So now, when the user presses the back button on the settings page, the Navigator.pop() call will return the data I need to the result variable in navdrawer.dart.

But my problem is ... how do I get this data to my home.dart screen/state?

X33
  • 1,310
  • 16
  • 37

3 Answers3

2

I'll suggest you to use provider, scoped_model or other state management techniques for this. The easiest (but also the worthless) solution would be to use a global variable.

However, there's a middle ground. For simplicity I'm using dynamic for the type of result, you'd better know what Settings return, so use that type instead.

Your home.dart file

class _HomePageState extends State<HomePage> {
  dynamic _result; // Create a variable. 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavDrawer(
        onResult: (result) {
          _result = result; // <-- This is your result. 
        }
      ),
    );
  }
}

Add following in your navdrawer.dart:

class NavDrawer extends StatelessWidget {

  // Add these two lines. 
  final ValueChanged onResult; 
  NavDrawer({this.onResult}); 

  // Other code ...

} 

Modify your onTap method inside navdrawer.dart file:

onTap: () async {
  final result = await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => Settings()),
  );
  onResult(result); // <-- Add this line. 
}   
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
0

Please set parameters into the pop method. Like

Navigator.pop(context,true)
Hasib Akon
  • 580
  • 6
  • 16
0

Define 'Static' global variable in homepage screen/widget Then call the variable from anywhere :

1- homepage :

Static String getData;

2- when returned to Drawer :

homepage.getData=value;
Navigator.pop();