首页 > 解决方案 > 如何在加载其余小部件之前执行函数 onPressed()?

问题描述

所以我有一个异步函数,当我点击日历中的一天时会执行该函数。如果在数据库中存储了当天的信息,我将结果添加到列表任务中。就是这个功能

// This code is suppose to get all the taskNames of user on clicked day
  Future<void> getUserEvents() async {
    //We get Collection of 'userAssignments' from database
    final CollectionReference userAssignments =
        Firestore.instance.collection('userAssignments');

    //We get current logged in user
    FirebaseUser user = await FirebaseAuth.instance.currentUser();

    //This is used to format a DateTime of selected day to String 'yyyy-MM-dd'
    var formater = new DateFormat('yyyy-MM-dd');
    String formatted = formater.format(_controller.selectedDay);

    //We get rid off a all the unneded data from list
    tasks.clear();

    //This is a query, We loop through entire collection and we look for a document
    // with email of logged in user and we look for a day that is
    // equal to selected formated day (variable formatted)

    userAssignments
        .where("userEmail", isEqualTo: user.email)
        .where("eventDayForCalendar", isEqualTo: formatted)
        .snapshots()
        .listen((data) => data.documents.forEach((doc) {

              // We get a taskName from that document and we add it to our local List tasks
              String taskName = doc["taskName"];

              tasks.add(taskName);
            }));
  }

这里是小部件的代码。在代码的底部,Column 负责为 List 任务中的每个元素显示一张卡片。


//This is the class in which you can initialize widgets
class _CalendarPageState extends State<CalendarPage> {
  final DatabaseService _dbServices = DatabaseService();
  final AuthService _auth = AuthService();

  //This List stores all found tasks while conducting a getUserEvents()
  List<String> tasks = new List<String>();

//Here is placed the code from above

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //This creates a box that sorrounds the calendar and makes it scrollable
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            TableCalendar(
              events: _events,
              //Set the calendar controler parameter
              calendarController: _controller,
              //Set the starting day of the week to monday
              startingDayOfWeek: StartingDayOfWeek.monday,
              //Set default calendar format to week
              initialCalendarFormat: CalendarFormat.week,
              onDaySelected: (day, events) async {

                //Here i call the function that executes query and 
                // stores results in list tasks
                await getUserEvents();
                setState(() {
                  _selectedEvents = events;
                });
              },
              //Start defining the calendar style
              calendarStyle: CalendarStyle(
                todayColor: Colors.green,
                selectedColor: Colors.blue,
              ),
              headerStyle: HeaderStyle(
                titleTextStyle: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                ),
                //Hide the formatter for week/month
                formatButtonShowsNext: false,
                formatButtonVisible: false,
                centerHeaderTitle: true,
              ),
            ),
            Column(
                children: tasks
                    .map((i) => new Card(
                            child: ListTile(
                          title: Text(i.toString()),
                          leading: Icon(Icons.assignment_turned_in),
                        )))
                    .toList())
          ],
        ),
      ),
   
    );
  }

这是在 Column Widget 之前加载函数时的外观

如果小部件在功能完成之前加载,这就是它在同一天的样子

是否有一个小部件可以暂停代码在他下方或内部执行?

标签: firebaseflutterasynchronousdartflutter-onpressed

解决方案


我认为如果您setState((){ tasks =tasks; });在 getUserEvents() 末尾添加,小部件应该重建。


推荐阅读