首页 > 解决方案 > 如何设置 Widget ListTile 隐藏

问题描述

ListTile如果获取空数据,我试图设置隐藏的小部件SharedPreferences,我尝试使用Visibility并且出现这样的错误

“未来”类型不是“小部件”类型的子类型

我的Widget build(BuildContext context)

 Widget build(BuildContext context) {
    return new Drawer(
        child: new ListView(
      children: <Widget>[
        new DrawerHeader(
          child: new Text("Menu"),
          decoration: new BoxDecoration(color: Colors.lightBlueAccent),
        ),
        new ListTile(
          title: new Text("Profile"),
          onTap: () {
            Navigator.pop(context);
            Navigator.push(
                context,
                new MaterialPageRoute(
                    builder: (context) => new ProfileScreen()));
          },
        ),
        new ListTile(
          title: new Text("Proposal List"),
          onTap: () {
            visibleMethod();
          },
        ),
        //MY PROBLEM HERE
        Visibility(
          visible: true, 
          child: listTileAju()),

        new ListTile(
          title: new Text("Sign Out"),
          onTap: () async {
            SharedPreferences pref = await SharedPreferences.getInstance();
            pref.remove("authorization");
            pref.remove("is_login");
            Navigator.pushReplacement(context,
                MaterialPageRoute(builder: (BuildContext ctx) => LoginPage()));
          },
        ),
      ],
    ));
  }

My Widget listTileAju()

  listTileAju() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      roleAju = (pref.getStringList('role_aju') ?? 'Something Went Wrong');
    });
    if (roleAju != null) {
      Visibility(
        visible: true,
        child: new ListTile(
          title: new Text("Aju List"),
          onTap: () {
            Navigator.pop(context);
            Navigator.push(context,
                new MaterialPageRoute(builder: (context) => new AjuScreen()));
          },
        ),
      );
    } else {
      Visibility(
        visible: false,
        child: new ListTile(
          title: new Text("Aju List"),
          onTap: null,
        ),
      );
    }
  }

如果 SharedPreferences 获取空数据,我希望小部件 ListTile 可以隐藏

标签: androidflutterdarthide

解决方案


请尝试以下代码:-

bool isShowListTile;

Widget listTileAju(){
  Visibility(
    visible: isShowListTile,
    child: new ListTile(
      title: new Text("Aju List"),
      onTap: () {
        Navigator.pop(context);
        Navigator.push(context,
            new MaterialPageRoute(builder: (context) => new AjuScreen()));
      },
    ),
  );
}

@override
void initState() {
  super.initState();

  SharedPreferences pref = await SharedPreferences.getInstance();
  roleAju = (pref.getStringList('role_aju') ?? 'Something Went Wrong');
  if (roleAju != null) {
    if (mounted) {
      setState(() {
        isShowListTile = true;
      });
    }
  } else {
    if (mounted) {
      setState(() {
        isShowListTile = false;
      });
    }
  }
}

推荐阅读