php - 如何检查用户是否通过php和mysql登录?

标签 php mysql flutter dart

我是 flutter 和编程的新手。我使用的是Flutter模板(github.com/mitesh77/Best-Flutter-UI-Templates),并向其添加了启动屏幕。现在,我想检查用户是否未登录,初始屏幕将不会加载,并且用户会看到登录页面。我在新项目中尝试了这个(flutter-examples.com/flutter-online-user-registration-using-php-mysql-server)并为我正常工作。
但是如何将其添加到以下代码中。
码:

void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await SystemChrome.setPreferredOrientations(<DeviceOrientation>[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
          .then((_) => runApp(MyApp()));
}


/* This is First Screen */
class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {


    return new SplashScreen(
        seconds: 5,
        navigateAfterSeconds: new AfterSplash(),
        title: new Text('Hello',
          style: new TextStyle(
              fontWeight: FontWeight.w700,
              fontFamily: 'IranYekan',
              fontSize: 30.0
          ),),
        image: new Image.asset('assets/images/splashImage.png'),
        backgroundColor: Colors.white,
        styleTextUnderTheLoader: new TextStyle(),
        photoSize: 110.0,
        onClick: ()=>print("Flutter Egypt"),
        loaderColor: Colors.blue
    );
  }
}

class AfterSplash extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Open route'),
          onPressed: () {
            // Navigate to second route when tapped.
            Navigator.push(context, MaterialPageRoute(builder: (context) => NavigationHomeScreen()),
            );
          },
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override

  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Platform.isAndroid ? Brightness.dark : Brightness.light,
      systemNavigationBarColor: Colors.white,
      systemNavigationBarDividerColor: Colors.grey,
      systemNavigationBarIconBrightness: Brightness.dark,
    ));
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale("fa", "IR"), // OR Locale('ar', 'AE') OR Other RTL locales
      ],
      locale: Locale("fa", "IR") // OR Locale('ar', 'AE') OR Other RTL locales
      ,title: 'Flutter UI',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: AppTheme.textTheme,
        platform: TargetPlatform.iOS,
      ),

        home: FirstRoute(),
        );
  }
}

class HexColor extends Color {
  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));

  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF' + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }
}

最佳答案

我要告诉你我在项目中所做的事情,
首先,您需要安装Sharedprefrence,然后在lib文件夹中创建文件,创建名为Utils的文件夹,您可以输入所需的任何名称,并在Utils文件夹中创建文件sharedpreference.dartlib\Utils\ps:您可以使用此文件添加更多数据,例如,如果api返回userid类型的内容,您可以在此处指定,并且可以使用sharedprefrence在整个屏幕上访问数据

class SharedPrefrence {
     Future<bool> setLoggedIn(bool status) async {
            final SharedPreferences prefs = await SharedPreferences.getInstance();
            return prefs.setBool("logged_in", status);
          }
        
          Future<bool> getLogedIn() async {
            final SharedPreferences prefs = await SharedPreferences.getInstance();
            return prefs.getBool("logged_in") ?? false;
          }
        Future<bool> setUserId(String userId) async {
          final SharedPreferences prefs = await SharedPreferences.getInstance();
          return prefs.setString("user_id", userId);
       }
    
      Future<String> getUserId() async {
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.getString("user_id") ?? '';
      }
}
登录页面
这是示例登录功能,其中我使用了首选项
void AppLogin(String username, String password) async {

    var response = await http.post(Urls.LOGIN,
        headers: {"Content-Type": "application/json"},
        body: json.encode({
          "User_Name": username,
          "Password": password,
        }));

    Map<String, dynamic> value = json.decode(response.body);
    if (response.statusCode == 200) {
      dialog.dismissProgressDialog(context);
      try {
        Map<String, dynamic> value = json.decode(response.body);
        SharedPrefrence().setLoggedIn(true);
        SharedPrefrence().setUserId(value['_id'].toString());

        Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (context) => DashboardScreen()),
            ModalRoute.withName("/login"));
      } catch (e) {
        e.toString();
      }
    }  else {
      dialog.dismissProgressDialog(context);
      var message = value['message'];
      CustomDialogs().showErrorAlert(context, message);
    }
  }
在初始屏幕中添加此函数,并在initState函数中调用函数startTime,在此初始屏幕中将显示3秒钟,然后将调用navigationPage,在该页面中,将检查共享偏好设置的登录状态(无论用户是否登录)如果不是,它将显示登录名,如果已登录,将重定向到dahsboard屏幕
 startTime() async {
    var _duration = new Duration(seconds: 3);
    return new Timer(_duration, navigationPage);
  }

  void navigationPage() {


    Future loginstatus = SharedPrefrence().getLogedIn();
    loginstatus.then((data) {
      if (data == true) {
        Navigator.pop(context, true);
        Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (context) => DashboardScreen()),
            ModalRoute.withName("/login"));
      } else {
        Navigator.pop(context, true);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => LoginScreen(),
          ),
        );
      }
    });
  }

关于php - 如何检查用户是否通过php和mysql登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62606600/

相关文章:

php - 如何获取站点上加载了 javascript/ajax 的 div 的内容?

PHP 将数字转换为单词

php - 如何在没有 Ajax 的情况下使用 Google Wallet 而不是像 Paypal 一样提交表单?

php 没有正确创建 mysql 列

php - 如何连接到数据库并从数据库中检索数据?

button - 如何创建带有彩色阴影的渐变按钮

PHP 使用与系统中安装的不同的curl 版本

MYSQL - 基于组 ID 或用户 ID 的分片

dart - 如何滑动到右侧的新页面而不是 flutter 的底部?

dart - 如何在项目构建器中显示来自 Firestore 的列表