flutter 没有为类型“Future”定义方法“map”[重复]

n53p2ov0  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(163)
    • 此问题在此处已有答案**:

What is a Future and how do I use it?(6个答案)
昨天关门了。
我正在编程一个Flutter健身房应用程序,我保存在一个 dart 文件中的每一个程序,每天的程序都是为了与项目ID,这是写像前:第1周第1天、第1周第2天...
同时,我正在使用Firebase Firestore来节省一周和一天,它工作正常没有问题。
我的问题是,当我想从firestore中获取周和日时,它是未来值,所以我需要在. then()内部做所有事情,这只适用于局部变量..,而在. then()外部,我的返回不知道这个值。
另一件事是我不能使用异步等待,因为它显示了一个错误:
A value of type 'Future<List<WorkoutData>>' can't be assigned to a variable of type 'List<WorkoutData>'.
请核对一下密码。
使用异步等待

class WorkoutsBloc extends Bloc<WorkoutsEvent, WorkoutsState> {
  WorkoutsBloc() : super(WorkoutsInitial());

List<WorkoutData> workouts= initialiseWorkoutList();


  @override
  Stream<WorkoutsState> mapEventToState(WorkoutsEvent event,) async* {
        if (event is WorkoutsInitialEvent) {
      GlobalConstants.workouts = await DataService.getWorkoutsForUser();
      for (int i = 0; i < workouts.length; i++) {
        final workoutsUserIndex =
        GlobalConstants.workouts.indexWhere((w) => w.id == workouts[i].id);
        if (workoutsUserIndex != -1) {
          workouts[i] = GlobalConstants.workouts[workoutsUserIndex];
        }
      }
      yield ReloadWorkoutsState(workouts: workouts);
    } else if (event is CardTappedEvent) {
      yield CardTappedState(workout: event.workout);
    }
  }

}

Future<String?> getWeek() async {
  FirebaseAuth auth=FirebaseAuth.instance;
  var userID=auth.currentUser?.uid;
  var collection = FirebaseFirestore.instance.collection("users");
  var docSnapshot = await collection.doc(userID.toString()).get();
  Map<String, dynamic>? data = docSnapshot.data();

  var weekNum = await data?["weekNumber"].toString();

  return Future(() => weekNum);

}

Future<String?> getDay() async {
  FirebaseAuth auth=FirebaseAuth.instance;
  var userID=auth.currentUser?.uid;
  var collection = FirebaseFirestore.instance.collection("users");
  var docSnapshot = await collection.doc(userID.toString()).get();
  Map<String, dynamic>? data = docSnapshot.data();

  var dayNum = await data?["dayInWeek"].toString();

  return Future.value(dayNum);

}

Future<List<WorkoutData>> initialiseWorkoutList() async{
var week=await getWeek();
var day=await getDay();
  List<WorkoutData> workouts = DataConstants.workouts
      .where((element) => element.id!.contains("Week${week}Day${day}"))
      .toList();

  workouts.addAll(DataConstants.homeWorkouts);

  return workouts;

  }

如果我在"mapEventToState"内部调用final myWorkouts = await workouts;,当然还有List<WorkoutData> workouts has to be Future<List<WorkoutData>> workouts,错误会将其放入其他文件
看看这个:

class WorkoutContent extends StatelessWidget {
  WorkoutContent({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: ColorConstants.homeBackgroundColor,
      height: double.infinity,
      width: double.infinity,
      child: _createHomeBody(context),
    );
  }

  Widget _createHomeBody(BuildContext context)  {
    final bloc = BlocProvider.of<WorkoutsBloc>(context);

    return BlocBuilder<WorkoutsBloc, WorkoutsState>(
        buildWhen: (_, currState) => currState is ReloadWorkoutsState,
        builder: (context, state) {
          return Padding(
            padding: const EdgeInsets.only(top: 50),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0),
                  child: Text(
                    TextConstants.workouts,
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                  ),
                ),
                const SizedBox(height: 5),
                Expanded(
                  child: ListView(
                    children:
                    bloc.workouts.map((e) => _createWorkoutCard(e)).toList(),
                  ),
                ),
              ],
          ),
          );
       },
    );
  }

  Widget _createWorkoutCard(WorkoutData workoutData) {

    return Padding(
      padding: const EdgeInsets.only(bottom: 20),
      child: WorkoutCard(workout: workoutData),
    );
  }
}

错误出现在:www.example.com((e)=〉_创建锻炼卡(e)). toList(),bloc.workouts.map((e) => _createWorkoutCard(e)).toList(),

The method 'map' isn't defined for the type 'Future'.
5lwkijsr

5lwkijsr1#

你在值的返回上做错了

Future<String?> getWeek() async {
  .....

  return Future(() => weekNum);

}

Future<String?> getDay() async {
  ....

  return Future.value(dayNum);

}

您需要像这样替换返回值。

Future<String?> getWeek() async {
      .....
    
      return weekNum;
    
    }
    
    Future<String?> getDay() async {
      ....
    
      return dayNum;
    
    }

相关问题