Home > OS >  how to move functions to a separated file Flutter?
how to move functions to a separated file Flutter?

Time:12-20

I have a function which is used in several files, in it I use setState(() {}); and some variables that are in the file, can I somehow separate it into another file and call it from there, and not write it on each page?

Here is an example of my function:

  Future addToFav(productId, int index) async {
    var url =
        '${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
    http.Response response = await http.get(
      Uri.parse(url),
    );
    dynamic body = jsonDecode(response.body);
    print(body['success']);
    print(body['message']);
    if(body['message'] == 'ADDED') {
      setState(() => _isFavLoading.add(index));
    } else {
      setState(() {
        _isFavLoading.remove(index);
          isFavorite = false;
      });
    }
  }

CodePudding user response:

Because you cannot update the state with setState() outside of the widget. You have to pass the logic that updates the state as parameter to the function, so you will get such function:

Future<void> addToFav({
  required int productId,
  required int index,
  VoidCallback? onAdded,
  VoidCallback? onRemoved,
}) async {
  var url =
      '${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
  http.Response response = await http.get(
    Uri.parse(url),
  );
  dynamic body = jsonDecode(response.body);
  print(body['success']);
  print(body['message']);
  if (body['message'] == 'ADDED') {
    onAdded?.call();
  } else {
    onRemoved?.call();
  }
}

In the widget you will call this function like this:

ElevatedButton(
    onPressed: () {
      addToFav(
        index: index,
        productId: productId,
        onAdded: () {
          setState(() => _isFavLoading.add(index));
        },
        onRemoved: () {
          setState(() {
            _isFavLoading.remove(index);
            isFavorite = false;
          });
        },
      );
    },
    child: Text('Fav'),
  )

CodePudding user response:

Create a new file and declare class with suitable class-name. i.e.

class Utility {

   String getText () {
      return "Test Text";
   }
}

In other files import it, and call it by instance.

Import: import 'utility.dart';


  Utility utils = new Utility();
  String text = utils.getText();

  • Related