Flutter提供者状态管理,注销概念 [英] Flutter provider state management, logout concept

查看:120
本文介绍了Flutter提供者状态管理,注销概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序实现自定义注销解决方案,无论用户当前在哪里,只要单击Logout button,应用程序都将导航回Login page.

I am trying to implement custom logout solution for my application, where no matter where user currently is, once the Logout button is clicked, app will navigate back to Login page.

我的想法是,与其在每个组件上侦听状态更改,不如在一个主组件上有一个侦听器-> MyApp.

My idea was, that instead of listening on every component for state changes, I would have one single listener on a master component -> MyApp.

为简单起见,我将项目精简到最低限度.这是我的Profile类的样子:

For the sake of simplicity, I have stripped down items to bare minimum. Here is how my Profile class could look like:

class Profile with ChangeNotifier {
  bool _isAuthentificated = false;
  bool get isAuthentificated => _isAuthentificated;
  set isAuthentificated(bool newVal) {
    _isAuthentificated = newVal;
    notifyListeners();
  }
}

现在,在Main下,我已经按照以下方式注册了该提供程序:

Now, under Main, I have registered this provider as following:

void main() => runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (_) => Profile(),
          )
        ],
        child: MyApp(),
      ),
    );

最后是MyApp组件:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Consumer<Profile>(
      builder: (context, profile, _) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            brightness: Brightness.light,
            primaryColor: Color.fromARGB(255, 0, 121, 107),
            accentColor: Color.fromARGB(255, 255, 87, 34),
          ),
          home: buildBasePage(context, profile),
        );
      },
    );
  }

  Widget buildBasePage(BuildContext context, Profile currentProfile) {
    return !currentProfile.isAuthentificated
        ? LoginComponent()
        : MyHomePage(title: 'Flutter Demo Home Page test');
  }
}

我的想法是,由于MyApp组件是 master ,因此我应该能够创建使用者,如果当前用户已通过身份验证,则该使用者将得到通知,并会做出相应的响应.

My idea was, that as MyApp component is the master, I should be able to create a consumer, which would be notified if current user is authentificated, and would respond accordingly.

发生的事情是,当我在MyHomePage组件,然后单击如下所示的Logout()方法:

What happens is, that when I am in e.g. MyHomePage component and I click Logout() method which looks like following:

  void _logout() {
    Provider.of<Profile>(context, listen: false).isAuthentificated = false;
  }

我希望更改属性后,初始的MyApp组件会做出反应并生成LoginPage;事实并非如此.我尝试将Consumer更改为Provider.of<Profile>(context, listen: false),但结果相同.

I would be expecting that upon changing property, the initial MyApp component would react and generate LoginPage; which is not the case. I have tried changing from Consumer to Provider.of<Profile>(context, listen: false) yet with the same result.

要使此概念生效,我需要做什么?这样做是否正确?

What do I need to do in order for this concept to work? Is it even correct to do it this way?

我的意思是,我肯定可以通过添加以下方法来更新Profile类:

I mean I could surely update my Profile class in a way, that I add the following method:

  logout(BuildContext context) {
    _isAuthentificated = false;

    Navigator.push(
        context, MaterialPageRoute(builder: (context) => LoginComponent()));
  }

然后简单地调用Provider.of<Profile>(context, listen: false).logout(),但是我认为Provider程序包是为此设计的……还是我缺少了什么?

And then simply call Provider.of<Profile>(context, listen: false).logout(), however I thought that Provider package was designed for this...or am I missing something?

在此问题上的任何帮助将不胜感激.

Any help in respect to this matter would be more than appreciated.

推荐答案

我不知道为什么它不适合您.这是我根据您的描述构建的完整示例.可行!

I don't know why it wasn't working for you. Here is a complete example I built based on your description. It works!

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Profile with ChangeNotifier {
  bool _isAuthentificated = false;

  bool get isAuthentificated {
    return this._isAuthentificated;
  }

  set isAuthentificated(bool newVal) {
    this._isAuthentificated = newVal;
    this.notifyListeners();
  }
}

void main() {
  return runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<Profile>(
          create: (final BuildContext context) {
            return Profile();
          },
        )
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Consumer<Profile>(
      builder: (final BuildContext context, final Profile profile, final Widget child) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(primarySwatch: Colors.blue),
          home: profile.isAuthentificated ? MyHomePage() : MyLoginPage(),
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Home [Auth Protected]")),
      body: Center(
        child: RaisedButton(
          child: const Text("Logout"),
          onPressed: () {
            final Profile profile = Provider.of<Profile>(context, listen: false);
            profile.isAuthentificated = false;
          },
        ),
      ),
    );
  }
}

class MyLoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Login")),
      body: Center(
        child: RaisedButton(
          child: const Text("Login"),
          onPressed: () {
            final Profile profile = Provider.of<Profile>(context, listen: false);
            profile.isAuthentificated = true;
          },
        ),
      ),
    );
  }
}

这篇关于Flutter提供者状态管理,注销概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆