从另一个文件将 var 导入 main.dart?

Importing var to main.dart from another file?

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');
  }
}

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

我希望从 checkContact.dart 获得在 main.dart 上显示的 $FamilyMember。上面的代码给我一个错误,说 FamilyMember 未定义print('$FamilyMember')checkContact.dart 上工作正常,但为什么在 main.dart 上出现问题?

首先,您需要在 checkContactPermission 函数之外定义 familyMember 变量。 然后将 checkContact.dart 导入 main.dart 文件(如果它们在单独的文件中)。

这将是结束代码。

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');
  }
}

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