dart - flutter:根据不同的状态路由到不同的页面

标签 dart flutter

尝试根据我的应用程序中的用户状态(登录或未登录)进行重定向,但它不会像我想要的那样工作,因为我不确定如何在方法中获取 BuildContext。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:t2/helpers/currentuser.dart';

import 'screens/dashboard.dart';
import 'screens/login.dart';

void main() => runApp(new MyApp());

CurrentUser user = new CurrentUser();

Future checkActiveUser() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  user.usr = prefs.get('usr');
  user.pwd = prefs.get('pwd');
  if (user.usr.length == 0 && user.pwd.length == 0) {
    user.isLoggedIn = false;
    Navigator.of(x).pushNamedAndRemoveUntil('/dashboard', (Route<dynamic> route) => false);
  } else {
    // Send to login screen
    user.isLoggedIn = false;
    Navigator.of(x).pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
  }

  return user.isLoggedIn;

  /*
// How to read/write to local storage
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
prefs.setInt('counter', counter);
*/
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
          // counter didn't reset back to zero; the application is not restarted.
          primarySwatch: Colors.blue,
        ),
        home: new MyHomePage(),
        routes: <String, WidgetBuilder>{
          '/dashboard': (BuildContext context) => new Dashboard(),
          '/login': (BuildContext context) => new Login()
        });
  }
}

class MyHomePage extends StatelessWidget {

   var isLoggedIn = checkActiveUser();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('Demo Building'),
        ),
        body: new Container(
            child: new Center(
          child: new Column(
            children: <Widget>[new Text('DASHBOARD')],
          ),
        )));
  }
}

如果您有不同方法的建议,我会洗耳恭听!我基本上想在应用程序加载时运行此检查并相应地重定向。

问候,鲍勃

更新代码:尝试了 Hadrien 的建议,并且更接近了一步。它现在运行并且我获得了联系人访问权限,但是出现以下错误:

'使用不包含导航器的上下文请求导航器操作。用于从 Navigator 推送或弹出路由的上下文必须是作为 Navigator 小部件后代的小部件的上下文。'

这是更新后的代码:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:t2/helpers/currentuser.dart';

import 'screens/dashboard.dart';
import 'screens/login.dart';

void main() => runApp(new MyApp());

CurrentUser user = new CurrentUser();

checkActiveUser(BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

try {
  user.usr = prefs.get('usr');
  user.pwd = prefs.get('pwd');

  if (user.usr.length == 0 && user.usr.length == 0) {
    user.isLoggedIn = false;
    Navigator
        .of(context)
        .pushNamedAndRemoveUntil('/dashboard', (Route<dynamic> route) => false);
  } else {
      throw new Exception('No user data found');
  }
} catch (e) {
    // Send to login screen
    user.isLoggedIn = false;
    Navigator
        .of(context)
        .pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
}

  /*
// How to read/write to local storage
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
prefs.setInt('counter', counter);
*/
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void initState() {
    super.initState();
    checkActiveUser(context);
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Welcome to Flutter',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('CADSYS'),
        ),
        body: new Center(
          child: new Text('Loading...'),
        ),
      ),
     routes: <String, WidgetBuilder> {
      '/dashboard': (BuildContext context) => new Dashboard(),
      '/login': (BuildContext context) => new Login()
    },
    );
  }
}

最佳答案

我可能会做一些不同的事情...而不是在函数中推送路由,在 StatefulWidget 中设置登录状态,然后设置 body 基于

正文:user.isLoggedIn ?新仪表板():新登录(),

然后在代码的其他地方,您需要检查事件用户并执行 setState((){ user.isLoggedIn = true; });(或 false)。

当登录状态发生变化时,您的 View 将自动更新为新的 Widget。

关于dart - flutter:根据不同的状态路由到不同的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49359706/

相关文章:

dart - 什么意思??在 Dart

android-studio - 错误 : Not found: 'dart:ui' export 'dart:ui' show Offset;

flutter - 如何从 Assets 中制作带有图片的图标?

list - 在 Flutter 中使用 Dart,如何添加到 map 列表内的 map 列表?

firebase - 有什么办法可以在FieldValue.arrayUnion中添加FieldValue.increment()?

dart - Flutter _TypeError(类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型)

flutter - 定期通知 - OneSignal API Flutter

list - 如何从列表内部访问实例方法?

flutter - 如何在 Dart 中以秒为单位添加纪元时间

flutter - -bash : flutter: command not found