'How to call Future Function to another class in flutter?

I am new in flutter. I created Drawer and loaded its header data from server by creating a future function. I want to recall this future function again from another class, so how can i do that.

I also tried to call by creating its class object like - Drawersetting object = new Drawersetting();

then - > object.function_name

But that function is not visible.

How to do that? Following whole class - >

        import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:mera_interest_flutter/Activity/BottomNavBar.dart';
    import 'package:mera_interest_flutter/Activity/Login.dart';
    import 'package:mera_interest_flutter/Custom/CustomClass.dart';
    import 'package:mera_interest_flutter/Fragments/AppHistoryTabScreen.dart';
    import 'package:mera_interest_flutter/Fragments/NotificationFragment.dart';
    import 'package:mera_interest_flutter/Fragments/PartnersScreen.dart';
    import 'package:mera_interest_flutter/Network/BaseURLHeaders.dart';
    import 'package:mera_interest_flutter/model/UserInfoDataModel.dart';
    import 'package:mera_interest_flutter/model/UserInfoModel.dart';
    import 'package:mera_interest_flutter/routes/Routes.dart';
    import '../Fragments/DiscoverScreen.dart';
    import 'package:flutter_session/flutter_session.dart';
    import 'package:mera_interest_flutter/Activity/UserProfileScreen.dart';
    import 'package:mera_interest_flutter/Fragments/AddManualFragment.dart';
    import 'package:mera_interest_flutter/Fragments/ContactUsScreen.dart';
    import 'package:mera_interest_flutter/Fragments/FAQFragment.dart';
    import 'package:mera_interest_flutter/Fragments/MessageFragment.dart';
    
    import '../Fragments/HomeFragment.dart';
    import '../Fragments/ZeroBalancePortFolioScreen.dart';
    import '../Fragments/SupportFragment.dart';
    import 'package:flutter_session/flutter_session.dart';
    import 'package:http/http.dart' as http;
    
    //for setting title name of side bar items
    class DrawerItem {
      String title;
      IconData icon;
    
      DrawerItem(this.title, this.icon);
    }
    
    //for setting title name of bottom bar items
    // class widgetBottomItems{
    //   String title;
    //   IconData icon;
    //   widgetBottomItems(this.title, this.icon);
    // }
    
    class DrawerSetting extends StatefulWidget {
    
      final drawerItems = [
        new DrawerItem("Portfolio", Icons.add),
        new DrawerItem("Zero Balance Portfolio", Icons.alarm),
        new DrawerItem("Message", Icons.message),
        new DrawerItem("My Info & Setting", Icons.settings),
        new DrawerItem("Support", Icons.help),
        new DrawerItem("FAQ", Icons.book_outlined),
        new DrawerItem("Contact Us", Icons.contact_phone_outlined),
        new DrawerItem("Logout", Icons.logout)
      ];
    
    
      @override
      State<StatefulWidget> createState() {
        return new HomePageState();
      }
    }
    
    class HomePageState extends State<DrawerSetting> {
      String _title;
    
      var session = FlutterSession();
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        getUserData();
        _title ="Discover";
      }
      void didUpdateWidget(covariant DrawerSetting oldWidget) {
        // TODO: implement didUpdateWidget
        super.didUpdateWidget(oldWidget);
        setState(() {
          getUserData();
          getNewProfile();
        });
    
      }
      bool is_new_profile = false;
      void getNewProfile()async{
        is_new_profile = await session.get("is_new_profile");
        print("sessionvalue = " + is_new_profile.toString());
        if(is_new_profile == true){
          setState(() {
            getUserData();
          });
        }
      }
    
      final Color myColor = Color(0xFF15A2EB);
      final Color myColorLightGray = Color(0xFF989E9E);
      final Color text_Semi_Black_Color = Color(0xFF414B51);
      final Color text_gray_color = Color(0xFF70787C);
    
      UserInfoDataModel _userInfoDataModel;
    
      String url = BaseURLHeaders().getBaseURl() + "";
      Map headers = BaseURLHeaders().getHeader();
    
    
    
      //bottom navigation
      int _selectedIndex = 0;
      var _screens = [
        DiscoverScreen(),
        HomeFragment(),
        PartnersScreen(),
        // HistoryScreen(),
        AppHistoryTabScreen(),
        NotificationFragment(),
      ];
      static const TextStyle optionStyle = TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
        color: Colors.red,
        fontFamily: "verdana_regular",
      );
    
      //for bottom items
      void _onItemTapped(int index) {
        setState(() {
          _selectedIndex = index;
          switch(index) {
            case 0: { _title = 'Discover'; }
            break;
            case 1: { _title = 'Portfolio'; }
            break;
            case 2: { _title = 'Partners'; }
            break;
            case 3: { _title = 'History'; }
            break;
          }
        });
      }
    
      int _selectedDrawerIndex = 0;
    
      String currentProfilePic =
          "https://service2home.in/wp-content/uploads/2021/01/rakesh.jpg";
    
      _getDrawerItemWidget(int pos) {
        switch (pos) {
          case 0:
            return new AddManualFdFragment();
            break;
          case 1:
            return new ZeroBalancePortFolioScreen();
            break;
          case 2:
            return MessageFragment();
            break;
          case 3:
            return new UserProfileScreen("drawer");
            break;
          case 4:
            return new SupportFragment();
            break;
          case 5:
            return new FAQFragment();
            break;
          case 6:
            return new ContactUsScreen();
            break;
          case 7:
            SystemNavigator.pop();
            //exit(0);
            break;
        }
      }
    
      //for drawer items
      _onSelectItem(int index) {
        setState(() => _selectedDrawerIndex = index);
        Navigator.of(context).pop(); // close the drawer
      }
    
      @override
      Widget build(BuildContext context) {
        //set portrait by default
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
        List<Widget> drawerOptions = [];
        for (var i = 0; i < widget.drawerItems.length; i++) {
          var d = widget.drawerItems[i];
          drawerOptions.add(new ListTile(
            leading: new Icon(
              d.icon,
            ),
            title: new Text(
              d.title,
              style: TextStyle(
                fontSize: 16,
                color: myColorLightGray,
                fontFamily: "verdana_regular",
              ),
            ),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          ));
        }
    
        //on backpress return to home screen , you can use it for drawer items
        return WillPopScope(
          onWillPop: () {
            if (_selectedIndex != 0 || _selectedDrawerIndex != 0) {
              setState(() {
                _selectedIndex = 0;
              });
              // _getDrawerItemWidget(_selectedIndex);
            } else {
              Navigator.pop(context, true);
            }
            return;
          },
          child: Scaffold(
            appBar: new AppBar(
              title: Row(
                children: [
                  Expanded(
                    child: new Text(
                                _title,
    
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontFamily: "verdana_regular"),
                    ),
                  ),
                  Expanded(
                    flex: 0,
                    child: Container(
                      margin: EdgeInsets.only(left: 80),
                      // width: MediaQuery.of(context).size.width * 0.25,
                      child: IconButton(
                          alignment: Alignment.centerRight,
                          icon: Icon(Icons.notifications_none),
                          onPressed: () => {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            NotificationFragment())),
                              }),
                    ),
                  ),
                ],
              ),
            ),
            drawer: new Drawer(
              child: SingleChildScrollView(
                child: new Column(
                  children: [
                    //header
                    UserAccountsDrawerHeader(
                      currentAccountPicture: Container(
                        child: new GestureDetector(
                            child: new Container(
                                decoration: new BoxDecoration(
                                    shape: BoxShape.circle,
                                    image: _userInfoDataModel != null
                                        ? new DecorationImage(
                                        fit: BoxFit.cover,
                                        image: new NetworkImage(
                                            _userInfoDataModel
                                                .profile_url)) :
                                    new DecorationImage(
                                        fit: BoxFit.cover,
                                        image: new AssetImage("assets/images/user.png"),
                                    ),
    
                                )
                            ),
                            onTap: () => {
                                  Navigator.of(context).pop(),
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            UserProfileScreen("header")),
                                  ),
                                }),
                      ),
                      accountName: _userInfoDataModel !=null ? new Text(
                        _userInfoDataModel.first_name + " " + _userInfoDataModel.last_name,
                        style: TextStyle(
                          fontSize: 18,
                          color: Colors.black,
                          fontFamily: "verdana_regular",
                        ),
                      ) : null,
                      accountEmail: _userInfoDataModel !=null ? new Text(
                        _userInfoDataModel.email,
                        style: TextStyle(
                          fontSize: 15,
                          color: Colors.white,
                          fontFamily: "verdana_regular",
                        ),
                      ) : null,
                    ),
                    Column(children: [
                      ListTile(
                          leading: Icon(Icons.add),
                          title: Text(
                            'Add Manual FD',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            // Navigator.pushReplacementNamed(context, Routes.addFd);
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => AddManualFdFragment()));
                          }),
                      ListTile(
                          leading: Icon(Icons.alarm),
                          title: Text(
                            'Zero Balance Portfolio',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        ZeroBalancePortFolioScreen()));
                          }),
                      ListTile(
                          leading: Icon(Icons.message),
                          title: Text(
                            'Message',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => MessageFragment()));
                          }),
                      ListTile(
                          leading: Icon(Icons.settings),
                          title: Text(
                            'MY Info & Setting',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        UserProfileScreen("header")));
                          }),
                      ListTile(
                          leading: Icon(Icons.help),
                          title: Text(
                            'Support',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => SupportFragment()));
                          }),
                      ListTile(
                          leading: Icon(Icons.bookmarks_outlined),
                          title: Text(
                            'FAQ',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => FAQFragment()));
                          }),
                      ListTile(
                          leading: Icon(Icons.contact_phone_outlined),
                          title: Text(
                            'Contact Us',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context).pop();
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => ContactUsScreen()));
                          }),
                      ListTile(
                          leading: Icon(Icons.logout),
                          title: Text(
                            'Logout',
                            style: TextStyle(
                              color: myColorLightGray,
                              fontSize: 15,
                              fontFamily: "verdana_regular",
                            ),
                          ),
                          onTap: () {
                            goToLogin();
                          }),
                    ])
                  ],
                ),
              ),
            ),
            body: _screens[_selectedIndex],
            /*_getDrawerItemWidget(_selectedDrawerIndex),*/
            bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              backgroundColor: myColor,
              items: const <BottomNavigationBarItem>[
                BottomNavigationBarItem(
                  icon: Icon(Icons.search),
                  label: 'Discover',
                ),
                BottomNavigationBarItem(
                  icon: ImageIcon(
                    AssetImage("assets/images/briefcase.png"),
                    // color: Colors.grey,
                  ),
                  label: 'Portfolio',
                ),
                BottomNavigationBarItem(
                  icon: ImageIcon(
                    AssetImage("assets/images/partner.png"),
                    // color: Colors.grey,
                  ),
                  label: 'Partners',
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.history),
                  label: 'History',
                ),
              ],
              currentIndex: _selectedIndex,
              selectedItemColor: Colors.black,
              unselectedItemColor: Colors.white,
              onTap: _onItemTapped,
            ),
            // bottomNavigationBar: BottomNavigationBar(),
          ),
        );
      }
    
      //go to news detail page
      void goToProfile_Screen(BuildContext ctx) {
        Navigator.of(ctx).push(
          MaterialPageRoute(
            builder: (_) {
              return UserProfileScreen("drawer");
            },
          ),
        );
      }
    
      //logout
      Future<void> goToLogin() async {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (BuildContext context) => Login()));
        await FlutterSession().set("isLogin", false);
        await FlutterSession().set("user_id", "");
        await FlutterSession().set("user_name", "");
        await FlutterSession().set("email", "");
        await FlutterSession().set("phone", "");
        await FlutterSession().set("account_status", "");
        await FlutterSession().set("isNewData", false);
      }
      //api get user info
      Future<UserInfoModel> getUserData() async {
        String user_id = "1";
        var mapData = new Map<String, dynamic>();
        mapData['user_id'] = user_id;
        // mapData['first_name'] = firstName;
    
        var response = await http.post(
          url,
          headers: headers,
          body: mapData,
        );
    
        if (response.statusCode == 200) {
          var res = json.decode(response.body);
          UserInfoModel _userInfoModel = UserInfoModel.fromJson(res);
          if (_userInfoModel.success == 1) {
            var data = res["data"];
            _userInfoDataModel = UserInfoDataModel.fromJson(data);
            // Toast.show("User Data Fetched", context,
            //     duration: Toast.LENGTH_SHORT, gravity: Toast.TOP);
    
            // CustomClass().makeToast("message", context);
    
            setState(() {
              print("responseBody: ${res}");
              print("responseData: ${data}");
              print("userInfoSuccess: ${_userInfoModel.success}");
              print("dataVaalue: ${data["email"]}");
              print("urlBelow: ${url}");
              print("headersBelow: ${headers}");
            });
          }
        }
      }
    
    }


Solution 1:[1]

A solution to your problem could be a static function inside a Drawer class. You could use this function in another file without initializing a new instance of a Drawer class by calling Drawer.function(). This function though can access only static variables of the parent class.

Also check this explanation: Class variables and methods - dart.dev

But:

Consider using top-level functions, instead of static methods, for common or widely used utilities and functionality.

Solution 2:[2]

You will need to create a function inside the calling class to call the Future function of another class. See the example below:

class ClassName {

 Future<void> functionName {
  something
  }
}

class CallingClassName {
 Final ClassName objName = ClassName();

 void callingFunciton {
  objName.functionName();
 }
}

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
Solution 2 sajan kumar