如何在其余小部件加载之前执行onPressed()函数?

时间:2020-06-27 17:22:54

标签: firebase flutter asynchronous dart flutter-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())
          ],
        ),
      ),
   
    );
  }

This is how it looks when function loads in before Column Widget

And this is how it looks on the same day if widget loads in before function is completed

也许有一个小部件可以暂停在他下面或他内部执行的代码?

1 个答案:

答案 0 :(得分:0)

我认为,如果在getUserEvents()的末尾添加def MyClass(object): def __init__(self): self.database =None self.sequence=None def main(self): if len(argv) != 3: print("Usage: python dna.py data.csv sequence.txt") exit(1) with open(argv[1]) as csv_file: self.database = csv.DictReader(csv_file) with open(argv[2]) as txt_file: self.sequence = txt_file.read() self.STR_searcher() def STR_searcher(self): STR_dict = dict.fromkeys(range(1, len(self.database.fieldnames))) for i in range(len(STR_dict)): for j in range(len(self.sequence)): print("hello") ,则应该重新构建窗口小部件。