在flutter中,如何根据登录的用户类型导航到特定主页?

时间:2019-07-31 14:10:01

标签: flutter

我的应用程序中要求包含两种类型的用户。 一种类型的用户(user_1)将在登录后有权访问表单页面,第二种类型的(admin)用户将有权访问user_1的已填写表单? 两个用户的登录屏幕都相同。根据登录凭据,将决定是浏览user_1页面还是管理页面。

该如何应对呢?要导航到不同用户的不同主页?

2 个答案:

答案 0 :(得分:1)

我有同样的事情要做。
我使用共享首选项来了解谁是此人(在您的情况下是管理员)。共享首选项是一种持久且安全的存储数据方式。 Here插件页面。

在我的初始化页面中,我检查共享首选项并根据结果重定向到该页面。

/// You can put the logo of your app
class LoadingScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    isLogged(context);
    return Scaffold(
      body: Center(
        child: Icon(
          Icons.beach_access,
        ),
      ),
    );
  }
}

Future isLogged(context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String isAdmin = prefs.getBool('isAdmin');
  if (uid == null) {
    /// If it's the first time, there is no shared preference registered
    Navigator.pushNamedAndRemoveUntil(...);
  } else {
    if (isAdmin) {
      /// If the user is an admin
      Navigator.pushNamedAndRemoveUntil(...);
    } else {
      /// If the user is not an admin
      Navigator.pushNamedAndRemoveUntil(...);
    }
  }
}

您只需要在用户连接时设置共享首选项:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isAdmin', true);

别忘了在main.dart中的加载/初始化屏幕上吃午餐

答案 1 :(得分:1)

这是我用来管理此问题的一种方式:

class App extends StatelessWidget {
  final String home;
  App({
    @required this.home,
  });

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      initialRoute: home,
      routes: routes,
    );
  }
}

然后在App类中:

package com.todo.service.todo;

import javax.persistence.*;

@Entity
@Table(name = "todo")
public class Todo {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int id;
    @Column(nullable = false)
    private String title;
    @Column(nullable = false)
    private boolean completed;


    public Todo(int id, String title, boolean completed) {
        this.id = id;
        this.title = title;
        this.completed = completed;
    }

    public Todo(){

    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }
}

当然,不要忘记导入所有必需的东西。 希望我的回答有帮助!