gpt4 book ai didi

flutter 一次介绍屏幕?

转载 作者:IT老高 更新时间:2023-10-28 12:31:45 31 4
gpt4 key购买 nike

我的应用有一个介绍屏幕,但每次打开应用时都会显示,我只需要第一次证明这一点

怎么做?

//THIS IS THE SCREEN COMES 1ST WHEN OPENING THE APP (SPLASHSCREEN)

class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();

//After 2seconds of time the Introscreen will e opened by bellow code
Timer(Duration(seconds: 2), () => MyNavigator.goToIntroscreen(context));
}

//The below code has the text to show for the spalshing screen
@override
Widget build(BuildContext context) {
return Scaffold(
body: new Center(
child: Text('SPLASH SCREEN'),
),
);
}
}

每次此屏幕打开介绍屏幕时都会延迟 2 秒。但我第一次只想要如何使用 sharedpreference??

请添加所需的代码。

最佳答案

如果您只想首次显示介绍屏幕,您需要在本地保存该用户已经看过介绍的内容。

对于这样的事情,你可以使用 Shared Preference .有一个flutter package对于您可以使用的共享偏好

已编辑:

请引用下面完整的测试代码来了解如何使用它:

import 'dart:async';

import 'package:after_layout/after_layout.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
color: Colors.blue,
home: new Splash(),
);
}
}

class Splash extends StatefulWidget {
@override
SplashState createState() => new SplashState();
}

class SplashState extends State<Splash> with AfterLayoutMixin<Splash> {
Future checkFirstSeen() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool _seen = (prefs.getBool('seen') ?? false);

if (_seen) {
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new Home()));
} else {
await prefs.setBool('seen', true);
Navigator.of(context).pushReplacement(
new MaterialPageRoute(builder: (context) => new IntroScreen()));
}
}

@override
void afterFirstLayout(BuildContext context) => checkFirstSeen();

@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Text('Loading...'),
),
);
}
}

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Hello'),
),
body: new Center(
child: new Text('This is the second page'),
),
);
}
}

class IntroScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('IntroScreen'),
),
body: new Center(
child: new Text('This is the IntroScreen'),
),
);
}
}

感谢 Ben B注意到 initState 中延迟的错误使用。我使用了 delay 因为有时上下文没有立即在 initState 内准备好。

所以现在我用 afterFirstLayout 替换了它,它已经准备好了上下文。您将需要安装包 after_layout .

关于 flutter 一次介绍屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50654195/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com