首页 > 解决方案 > 我如何放置条件语句以根据颤动中的用户类型验证脚手架中 FloatingActionButton 的视图?

问题描述

我只是在努力使用带有三元运算符和 if 语句的 FloatingActionButton 来验证。这里是代码

return Scaffold(
  resizeToAvoidBottomPadding: false,
  key: key,
  appBar: AppBar(
    title: Text('profile list'),
    flexibleSpace: header(),
  ),
  body: FutureBuilder<List<Leave>>(
    future: fetchLeave(http.Client()),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? profileListView(leave: snapshot.data)         //using this class variable 
          : Center(child: CircularProgressIndicator());
    },
  ),
  floatingActionButton: new FloatingActionButton(
    child: Icon(Icons.add),
    onPressed: () {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => ProfileForm(),
        ),
      );
    },
  ),
);

因此,为了使用 userType 作为学生/教师/管理员来验证它,我需要将 FloatingActionButton 放在条件语句中。所以我试过一个。

floatingActionButton:
      (profileListView().leave[0].userdetails.userType == "student")    //using the variable of another class
          ? new FloatingActionButton(
              //other codes
            )
          : new FloatingActionButton(
              //other codes
            ),

但它在 NULL 处调用函数

错误图片

请帮我解决这个错误...

配置文件列表视图()

class ProfileListView extends StatelessWidget {
  final List<Leave> leave;                 //fetching this variable
   
  const ProfileListView({Key key, this.leave}) : super(key: key);
   Widget build(BuildContext context) {
   
     //other codes

   }
}

标签: flutterdart

解决方案


profileListView().leave为 null,因为您创建了profileListView. 要leave在 FloatingActionButton 中获取列表,您可以使用 FutureBuilder 包装整个 Scaffold 而不仅仅是其body参数:

Widget build(...) {
  return FutureBuilder(
    future: fetchLeave(...),
    builder: (context, snaphot) => Scaffold(
      body: snapshot.hasData ? ... : CircularProgressIndicator(),
      floatingActionButton: snapshot.hasData && snapshot.data[0]... ? 
        FloatingActionButton(...) : 
        null,
    ),
  );
}

这样,您的 body 和 button 将始终可以访问相同的同步状态。


推荐阅读