SharedPreferences值需要每隔一段时间重置一次

问题描述 投票:0回答:1

所以,在这段包含的flutter代码中,我使用了一个if循环,在这个循环中,我使用了一个if循环。checkFirstSeen() 来设置我的 seen 布林值。这将使我的 SharedPreferences 值的应用程序。然而,在每一次重启应用程序时,我必须按下GotoHomepage按钮,而不是它自动地根据GotoHomepage按钮来工作。SharedPreferences 设置的值。我怎样才能解决这个问题?

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:audiotest/UI/homepage.dart';

void main() => runApp(new MaterialApp(
        title: "TestAudio",
        initialRoute: '/intro_route',
        routes: {
          '/intro_route': (context) => IntroScreen(),
          '/homescreen_route': (context) => MainPersistentTabBar2(),
        }));

class IntroScreen extends StatefulWidget {
  @override
  IntroScreenstate2 createState() => IntroScreenstate2();
}

class IntroScreenstate2 extends State<IntroScreen> {
  bool buttonstatus = true;
  Future checkFirstSeen() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool seen = (prefs.getBool('seen') ?? false);
    prefs.setBool('seen', false);
    if (buttonstatus == false) {

      prefs.setBool('seen', true); 
    }



    if (seen == true) {
      Navigator.pushNamed(context, '/homescreen_route');

    } else {

    }
  }

  @override
  void initState() {
    super.initState();
    new Timer(new Duration(milliseconds: 1), () {

      checkFirstSeen();
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Text('This is the placeholder for the TOS'),
            new MaterialButton(
              child: new Text('Go to Home Page'),
              onPressed: () {
                buttonstatus = false;
                checkFirstSeen();
                //Navigator.pushNamed(context, '/homescreen_route');
              },
            )
          ],
        ),
      ),
    );
  }
}
flutter dart sharedpreferences
1个回答
0
投票

你可以复制粘贴运行完整的代码,下面你可以得到 seenmain() 并检查 seen 直接在 initialRoute

代码段

bool seen;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SharedPreferences prefs = await SharedPreferences.getInstance();

  seen = await prefs.getBool("seen");
  await prefs.setBool("seen", true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ...
      initialRoute:
          seen == false || seen == null ? "/intro_route" : "/homescreen_route",
      routes: {
        '/homescreen_route': (context) => MainPersistentTabBar2(
              title: "demo",
            ),
        "/intro_route": (context) => IntroScreen(),
      },
    );
  }
}

工作示范

enter image description hereenter image description here

全码

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

bool seen;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SharedPreferences prefs = await SharedPreferences.getInstance();

  seen = await prefs.getBool("seen");
  await prefs.setBool("seen", true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute:
          seen == false || seen == null ? "/intro_route" : "/homescreen_route",
      routes: {
        '/homescreen_route': (context) => MainPersistentTabBar2(),
        "/intro_route": (context) => IntroScreen(),
      },
    );
  }
}

class MainPersistentTabBar2 extends StatefulWidget {
  @override
  MainPersistentTabBarState2 createState() => MainPersistentTabBarState2();
}

class MainPersistentTabBarState2 extends State<MainPersistentTabBar2> {
  Brightness brightness;
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.blue,
        brightness: Brightness.dark,
      ),
      home: DefaultTabController(
        length: 4,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              isScrollable: true,
              tabs: <Widget>[
                Container(
                  width: 90,
                  height: 40,
                  alignment: Alignment.center,
                  child: Text("Session 1"),
                ),
                Container(
                  width: 90,
                  height: 40,
                  alignment: Alignment.center,
                  child: Text("Session 2"),
                ),
                Container(
                  width: 90,
                  height: 40,
                  alignment: Alignment.center,
                  child: Text("Session 3"),
                ),
                Container(
                  width: 90,
                  height: 40,
                  alignment: Alignment.center,
                  child: Text("Session 4"),
                ),
              ],
            ),
            title: Text('Own The Tone '),
            /*actions: <Widget>[
              PopupMenuButton<String>(
                onSelected: _choiceAction,
                itemBuilder: (BuildContext context) {
                  return Constants.choices.map((String choice) {
                    return PopupMenuItem<String>(
                      value: choice,
                      child: Text(choice),
                    );
                  }).toList();
                },
              )
            ],*/
          ),
          body: TabBarView(
            children: <Widget>[
              FirstScreen(),
              Center(child: Text("Sample two")),
              Center(child: Text("Sample three")),
              Center(child: Text("Sample four")),
            ],
          ),
        ),
      ),
    );
  }

  // This area controls the settings menus
  /* void _choiceAction(String choice) {
    if (choice == Constants.about) {
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('About the app'),
          ),
          body: new PageView(),
        );
      }));
    } else if (choice == Constants.settings) {
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new Scaffold(

          appBar: new AppBar(
            title: new Text('Settings'),
          ),
          body: new Container(
              child: Center(
                child: Text('placeholder'),
              )),
        );
      }));
    }
  }*/
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("First Screen"),
        ),
        body: Text("First"));
  }
}

class IntroScreen extends StatefulWidget {
  @override
  _IntroScreenState createState() => _IntroScreenState();
}

class _IntroScreenState extends State<IntroScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Introduction"),
        ),
        body: Text("Intro"));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.