Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 检查应用程序是否在第一次运行时出现颤振_Dart_Flutter - Fatal编程技术网

Dart 检查应用程序是否在第一次运行时出现颤振

Dart 检查应用程序是否在第一次运行时出现颤振,dart,flutter,Dart,Flutter,基本上,我希望有一个屏幕/视图,当用户第一次打开应用程序时打开。这将是一个登录屏幕类型的东西 使用。您可以使用FutureBuilder阅读它,例如,您可以检查是否有名为welcome的bool。这是我在代码中的实现: return new FutureBuilder<SharedPreferences>( future: SharedPreferences.getInstance(), builder: (BuildContext con

基本上,我希望有一个屏幕/视图,当用户第一次打开应用程序时打开。这将是一个登录屏幕类型的东西

使用。您可以使用
FutureBuilder
阅读它,例如,您可以检查是否有名为
welcome
的bool。这是我在代码中的实现:

return new FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder:
          (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return new LoadingScreen();
          default:
            if (!snapshot.hasError) {
              @ToDo("Return a welcome screen")
              return snapshot.data.getBool("welcome") != null
                  ? new MainView()
                  : new LoadingScreen();
            } else {
              return new ErrorScreen(error: snapshot.error);
            }
        }
      },
    );
返回新的FutureBuilder(
future:SharedReferences.getInstance(),
建设者:
(BuildContext上下文,异步快照){
交换机(快照.连接状态){
案例连接状态。无:
案例连接状态。正在等待:
返回新的加载屏幕();
违约:
如果(!snapshot.hasError){
@ToDo(“返回欢迎屏幕”)
返回snapshot.data.getBool(“欢迎”)!=null
?新的主视图()
:新加载屏幕();
}否则{
返回新的ErrorScreen(错误:snapshot.error);
}
}
},
);

以上代码可以很好地工作,但对于初学者,我让它变得有点简单 main.dart

import 'package:flutter/material.dart';
import 'package:healthtic/IntroScreen.dart';
import 'package:healthtic/user_preferences.dart';
import 'login.dart';
import 'profile.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  // This widget is the root of your application.

  bool isLoggedIn = false;

  MyAppState() {
    MySharedPreferences.instance
        .getBooleanValue("isfirstRun")
        .then((value) => setState(() {
      isLoggedIn = value;
    }));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        //if true return intro screen for first time Else go to login Screen
        home: isLoggedIn ? Login() : IntroScreen());
  }
}
导入“包装:颤振/材料.省道”;
导入“package:healthtic/IntroScreen.dart”;
导入“package:healthtic/user_preferences.dart”;
导入“login.dart”;
导入“profile.dart”;
void main(){
runApp(MyApp());
}
类MyApp扩展了StatefulWidget{
@凌驾
状态createState(){
//TODO:实现createState
返回MyAppState();
}
}
类MyAppState扩展了状态{
//此小部件是应用程序的根。
bool isLoggedIn=false;
MyAppState(){
MySharedPreferences.instance
.getBooleanValue(“isfirstRun”)
.然后((值)=>设置状态(){
isLoggedIn=值;
}));
}
@凌驾
小部件构建(构建上下文){
返回材料PP(
debugShowCheckedModeBanner:false,
标题:“颤振演示”,
//如果为真,则第一次返回介绍屏幕,否则转到登录屏幕
主页:isLoggedIn?登录():IntroScreen());
}
}
然后分享偏好 MySharedPreferences

import 'package:shared_preferences/shared_preferences.dart';

class MySharedPreferences {
  MySharedPreferences._privateConstructor();

  static final MySharedPreferences instance =
  MySharedPreferences._privateConstructor();
  setBooleanValue(String key, bool value) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    myPrefs.setBool(key, value);
  }

  Future<bool> getBooleanValue(String key) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    return myPrefs.getBool(key) ?? false;
  }
}
import'package:shared_preferences/shared_preferences.dart';
类MySharedPreferences{
MySharedPreferences._privateConstructor();
静态最终MySharedPreferences实例=
MySharedPreferences._privateConstructor();
setBooleanValue(字符串键,布尔值)异步{
SharedReferences myPrefs=等待SharedReferences.getInstance();
myPrefs.setBool(键,值);
}
未来getBooleanValue(字符串键)异步{
SharedReferences myPrefs=等待SharedReferences.getInstance();
返回myPrefs.getBool(键)?false;
}
}
然后创建两个dart文件IntroScreenLogin 当用户第一次运行应用程序删除应用程序或清除缓存时,简介屏幕将只显示一次 内部屏幕

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:healthtic/SliderModel.dart';
import 'package:healthtic/login.dart';
import 'package:healthtic/user_preferences.dart';
import 'package:shared_preferences/shared_preferences.dart';

class IntroScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Healthtic",
      home: IntorHome(),
      debugShowCheckedModeBanner: false,
    );
  }
}
class IntorHome extends StatefulWidget {
  @override
  _IntorHomeState createState() => _IntorHomeState();
}

class _IntorHomeState extends State<IntorHome> {
  List<SliderModel> slides=new List<SliderModel>();
  int currentIndex=0;

  PageController pageController=new PageController(initialPage: 0);


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    slides=getSlides();
  }

  Widget pageIndexIndicator(bool isCurrentPage) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 2.0),
      height: isCurrentPage ? 10.0 : 6.0,
      width: isCurrentPage ? 10.0 :6.0,
      decoration: BoxDecoration(
          color: isCurrentPage ? Colors.grey : Colors.grey[300],
          borderRadius: BorderRadius.circular(12)
      ),
    );

  }
  @override
  Widget build(BuildContext context) {


    return Scaffold(

      body: PageView.builder(

          controller: pageController,
          onPageChanged: (val){
            setState(() {
              currentIndex=val;

            });
          },
          itemCount: slides.length,
          itemBuilder: (context,index){

            return SliderTile(


              ImageAssetPath: slides[index].getImageAssetPath(),
              title: slides[index].getTile(),
              desc: slides[index].getDesc(),


            );
          }),
      bottomSheet: currentIndex != slides.length-1 ? Container(
        height:  Platform.isIOS ? 70:60,
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            GestureDetector(
                onTap: (){
                  pageController.animateToPage(slides.length-1, duration: Duration(
                    microseconds: 400,
                  ), curve: Curves.linear);
                },
                child: Text("Skip")
            ),
            Row(
              children: <Widget>[
                for(int i=0;i<slides.length;i++) currentIndex == i ?pageIndexIndicator(true): pageIndexIndicator(false)
              ],
            ),
            GestureDetector(
                onTap: (){
                  pageController.animateToPage(currentIndex+1, duration: Duration(
                      microseconds: 400
                  ), curve: Curves.linear);
                },
                child: Text("Next")
            ),
          ],
        ),
      ) : Container(
        alignment: Alignment.center,
        width: MediaQuery.of(context).size.width,
        height: Platform.isIOS ? 70:60,
        color: Colors.blue,
        child:
        RaisedButton(
          child: Text("Get Started Now",style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w300
          ),
          ),
          onPressed: (){
            MySharedPreferences.instance
                .setBooleanValue("isfirstRun", true);

            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (_) => Login()),
            );
          },
        ),

      ),
    );
  }
}
class SliderTile extends StatelessWidget {
  String ImageAssetPath, title, desc;

  SliderTile({this.ImageAssetPath, this.title, this.desc});

  @override
  Widget build(BuildContext context) {
    return Container(

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,

        children: <Widget>[

          Image.asset(ImageAssetPath),
          SizedBox(height: 20,),
          Text(title),
          SizedBox(height: 12,),
          Text(desc),
        ],
      )
      ,
    );
  }
}
import 'package:flutter/material.dart';
import 'package:healthtic/user_preferences.dart';
import 'profile.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoginState();
  }
}

class LoginState extends State<Login> {
  TextEditingController controllerEmail = new TextEditingController();
  TextEditingController controllerUserName = new TextEditingController();
  TextEditingController controllerPassword = new TextEditingController();

  @override
  Widget build(BuildContext context) {

    final formKey = GlobalKey<FormState>();

    // TODO: implement build
    return SafeArea(
      child: Scaffold(
          body: SingleChildScrollView(
            child: Container(
              margin: EdgeInsets.all(25),
              child: Form(
                key: formKey,
                autovalidate: false,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text("Email Id:", style: TextStyle(fontSize: 18)),
                        SizedBox(width: 20),
                        Expanded(
                          child: TextFormField(
                            controller: controllerEmail,
                            decoration: InputDecoration(
                              hintText: "Please enter email",
                            ),
                            keyboardType: TextInputType.emailAddress,
                            validator: (value) {
                              if (value.trim().isEmpty) {
                                return "Email Id is Required";
                              }
                            },
                          ),
                        )
                      ],
                    ),
                    SizedBox(height: 60),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text("UserName:", style: TextStyle(fontSize: 18)),
                        SizedBox(width: 20),
                        Expanded(
                          child: TextFormField(
                              decoration: InputDecoration(
                                hintText: "Please enter username",
                              ),
                              validator: (value) {
                                if (value.trim().isEmpty) {
                                  return "UserName is Required";
                                }
                              },
                              controller: controllerUserName),
                        )
                      ],
                    ),
                    SizedBox(height: 60),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text("Password:", style: TextStyle(fontSize: 18)),
                        SizedBox(width: 20),
                        Expanded(
                          child: TextFormField(
                              decoration: InputDecoration(
                                hintText: "Please enter password",
                              ),
                              obscureText: true,
                              validator: (value) {
                                if (value.trim().isEmpty) {
                                  return "Password is Required";
                                }
                              },
                              controller: controllerPassword),
                        )
                      ],
                    ),
                    SizedBox(height: 100),
                    SizedBox(
                      width: 150,
                      height: 50,
                      child: RaisedButton(
                        color: Colors.grey,
                        child: Text("Submit",
                            style: TextStyle(color: Colors.white, fontSize: 18)),
                        onPressed: () {
                          if(formKey.currentState.validate()) {
                            var getEmail = controllerEmail.text;
                            var getUserName = controllerUserName.text;
                            var getPassword = controllerPassword.text;
                            
                            MySharedPreferences.instance
                                .setBooleanValue("loggedin", true);

                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (_) => Profile()),
                            );
                          }
                        },
                      ),
                    )
                  ],
                ),
              ),
            ),
          )),
    );
  }
}
导入'dart:io';
进口“包装:颤振/材料.省道”;
导入“package:healthtic/SliderModel.dart”;
导入“package:healthtic/login.dart”;
导入“package:healthtic/user_preferences.dart”;
导入“package:shared_preferences/shared_preferences.dart”;
类IntroScreen扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“Healthtic”,
home:IntorHome(),
debugShowCheckedModeBanner:false,
);
}
}
类IntorHome扩展StatefulWidget{
@凌驾
_IntorHomeState createState()=>\u IntorHomeState();
}
类_IntorHomeState扩展状态{
列表幻灯片=新列表();
int currentIndex=0;
PageController PageController=新的PageController(初始页:0);
@凌驾
void initState(){
//TODO:实现initState
super.initState();
slides=getSlides();
}
小部件页面索引指示器(bool isCurrentPage){
返回容器(
边缘:边缘组。对称(水平:2.0),
高度:isCurrentPage?10.0:6.0,
宽度:isCurrentPage?10.0:6.0,
装饰:盒子装饰(
颜色:isCurrentPage?颜色。灰色:颜色。灰色[300],
边界半径:边界半径。圆形(12)
),
);
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:PageView.builder(
控制器:页面控制器,
onPageChanged:(val){
设置状态(){
currentIndex=val;
});
},
itemCount:slides.length,
itemBuilder:(上下文,索引){
返回滑块(
ImageAssetPath:幻灯片[索引]。getImageAssetPath(),
标题:幻灯片[索引].getTile(),
desc:slides[index].getDesc(),
);
}),
底页:currentIndex!=slides.length-1?容器(
高度:平台isIOS?70:60,
填充:边缘组。对称(水平:20),
孩子:排(
mainAxisAlignment:mainAxisAlignment.spaceBetween,
儿童:[
手势检测器(
onTap:(){
pageController.animateToPage(slides.length-1,持续时间:持续时间(
微秒:400,
),曲线:曲线。线性);
},
子项:文本(“跳过”)
),
划船(
儿童:[
对于(int i=0;i Login()),
);
},
),
),
);
}
}
类SliderTile扩展了无状态小部件{
字符串ImageAssetPath,title,desc;
SliderTile({this.ImageAssetPath,this.title,this.desc});
@凌驾
小部件构建(构建上下文){
返回容器(
子:列(
crossAxisAlignment:crossAxisAlignment.center,
mainAxisSize:mainAxisSize.max,
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
Image.asset(ImageAssetPath),
尺寸箱(高度:20,),
正文(标题),
尺寸箱(高度:12)