Home > Net >  Importing var to main.dart from another file?
Importing var to main.dart from another file?

Time:02-27

on checkContact.dart

Future<void> checkContactPermission() async {
  var status = await Permission.contacts.status;
  if (!status.isGranted) {
    PermissionStatus permissionStatus = await Permission.contacts.request();
    status = await Permission.contacts.status;
    if (status.isDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
    }
  }
  if (status.isGranted) {
    var contacts = await ContactsService.getContacts(withThumbnails: false);
    var list = contacts;
    list.shuffle();
    var FamilyMember = (list.first.phones?.first.value);
    await FlutterPhoneDirectCaller.callNumber('$FamilyMember');
  }
}

on main.dart

AwesomeDialog(
    context: context,
    dialogType: DialogType.SUCCES,
    borderSide:
    const BorderSide(color: Colors.green, width: 3),
    width: double.infinity,
    buttonsBorderRadius:
    const BorderRadius.all(Radius.circular(2)),
    animType: AnimType.TOPSLIDE,
    title: 'Family member call receiver',
    desc: '$FamilyMember',   <------ here is the problem

I wish to get the $FamilyMember displayed on main.dart from checkContact.dart. The code above give me an error saying FamilyMember isn't defined. print('$FamilyMember') worked fine on checkContact.dart but why is that the problem occur when it is on main.dart?

CodePudding user response:

First you need to define the familyMember variable outside of the checkContactPermission function. Then import the checkContact.dart into main.dart file if they're in separate files.

This will be the end code.

On checkContact.dart

var familyMember = '';

Future<void> checkContactPermission() async {
  var status = await Permission.contacts.status;
  if (!status.isGranted) {
    PermissionStatus permissionStatus = await Permission.contacts.request();
    status = await Permission.contacts.status;
    if (status.isDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
    }
  }
  if (status.isGranted) {
    var contacts = await ContactsService.getContacts(withThumbnails: false);
    var list = contacts;
    list.shuffle();
    familyMember = (list.first.phones?.first.value ?? '');
    await FlutterPhoneDirectCaller.callNumber('$familyMember');
  }
}

On main.dart

import 'checkContact.dart';

AwesomeDialog(
    context: context,
    dialogType: DialogType.SUCCES,
    borderSide:
    const BorderSide(color: Colors.green, width: 3),
    width: double.infinity,
    buttonsBorderRadius:
    const BorderRadius.all(Radius.circular(2)),
    animType: AnimType.TOPSLIDE,
    title: 'Family member call receiver',
    desc: '$familyMember',   <------ the problem will go away
  • Related