Home > Back-end >  How to move classes and functions to a separate file in Flutter/Dart?
How to move classes and functions to a separate file in Flutter/Dart?

Time:07-10

Good day! I am new to Flutter/Dart. And the more I experiment, the bigger my main file gets. Obviously, I need a separate file in which I will store all the classes and functions that I will refer to in the future.

I have a separate screen with what I need. Here is its code:

//Internet route
class InternetRoute extends StatefulWidget {
  const InternetRoute({Key? key}) : super(key: key);

  @override
  State<InternetRoute> createState() => _InternetRouteState();
}

class _InternetRouteState extends State<InternetRoute> {
  bool ActiveConnection = false;
  String T = "";
  Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
        showInternetDialog(context);
      });
    }
  }
  @override
  void initState() {
    CheckUserConnection();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}


//Alert Dialog about Internet connection
showInternetDialog(BuildContext context) {

  // set up the button
  Widget okButton = Center(
    child: TextButton(
      child: Text("OK"),
      onPressed: () {
        Navigator.of(context).pop(); // dismiss dialog
      },
    ),
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    // title: Text("My title"),
    content: Text("Internet connection required"),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );

I want to create a my classes.dart file that will gradually populate with the most commonly used things. In particular, I need class _InternetRouteState and showInternetDialog.

How to transfer them to a new file? I completely copied the code of that screen. Is it correct? Would that be enough to then refer to them in main.dart (after import)? Will all their variables be visible to my screens as well?

CodePudding user response:

Create a new dart file. Name it internet_dialog_handler.dart. Add this to the file

class InternetDialogHandler{
//Alert Dialog about Internet connection
showInternetDialog(BuildContext context) {

  // set up the button
  Widget okButton = Center(
    child: TextButton(
      child: Text("OK"),
      onPressed: () {
        Navigator.of(context).pop(); // dismiss dialog
      },
    ),
  );

  // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    // title: Text("My title"),
    content: Text("Internet connection required"),
    actions: [
      okButton,
    ],
  );

  // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

In internetRoute use this

//Internet route
class InternetRoute extends StatefulWidget {
  const InternetRoute({Key? key}) : super(key: key);

  @override
  State<InternetRoute> createState() => _InternetRouteState();
}

class _InternetRouteState extends State<InternetRoute> {
  bool ActiveConnection = false;
  String T = "";
 InternetDialogHandler _internetDialogHandler = InternetDialogHandler();
  Future CheckUserConnection() async {
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          ActiveConnection = true;
          T = "Turn off the data and repress again";
        });
      }
    } on SocketException catch (_) {
      setState(() {
        ActiveConnection = false;
        T = "Turn On the data and repress again";
      
  //Use the variable here to access the method in that class 
_internetDialogHandler.showInternetDialog(context);
      });
    }
  }
  @override
  void initState() {
    CheckUserConnection();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GeeksforGeeks"),
      ),
      body: Column(
        children: [
          Text("Active Connection? $ActiveConnection"),
          const Divider(),
          Text(T),
          OutlinedButton(
              onPressed: () {
                CheckUserConnection();
              },
              child: const Text("Check"))
        ],
      ),
    );
  }
}

CodePudding user response:

use terminal to create new file:

   $ cd lib   (changing directory to lib)
   $ touch desired_file_name.dart (to create file)
   $ cd (changing directory to initialpoint)

or if you want to create folder in lib folder then:

   $ cd lib
   $ mkdir desired_folder_name (creating folder)
   $ cd foldername
   $ touch desired_file_name.dart
   $ cd

thats all , copy paste and import files.

  • Related