Flutter提供商状态管理,注销概念

时间:2020-02-07 06:58:50

标签: flutter state-management flutter-provider flutter-state

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

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

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

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

现在,我已经在Main下注册了该提供者,如下所示:

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 ,因此我应该能够创建使用者,如果当前用户已通过身份验证,则该使用者将得到通知,并做出相应的响应。

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

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

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

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

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

  logout(BuildContext context) {
    _isAuthentificated = false;

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

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

在这方面的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

我不知道为什么它对您不起作用。这是我根据您的描述构建的完整示例。可行!

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;
          },
        ),
      ),
    );
  }
}

答案 1 :(得分:2)

您无需传递listen:false,只需致电

Provider.of<Profile>(context).logout()

所以您的个人资料类看起来像

      class Profile with ChangeNotifier {
  bool isAuthentificated = false;


  logout() {
    isAuthentificated = false;
    notifyListeners();
  }
}