首页 > 解决方案 > 为什么空变量在条件下分配不为空?

问题描述

我有一个条件语句让登录用户在启动屏幕后保持抖动,当列表为空时导航到 login() 并且当它有值导航时引入,但是虽然列表 (values_list_r) 为空并且“a”应该是null(并打印 null),它在 navigateAfterSeconds 中认为“非 null”并导航到介绍(),我的错误在哪里?

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

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

class _MyAppState extends State<MyApp> {
@override
var a;


 String initState() {
 super.initState();
   setState(() {

   //my sqlite class 
   ValuesDbprovider vdbhelper = new ValuesDbprovider();
   vdbhelper.fetchValues();

   //list has returned by fetchvalue() and currently is null and empty
   a =values_list_r.map((e) => e.user_no ).toList();

   //this printed a:  , means a is null
   print("a:$a" );
 });

}


Widget build(BuildContext context) {

return MaterialApp(
  home: Container(
    decoration: BoxDecoration(
        gradient: LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: [Color(0xFFFF1844), Color(0xFFFFD200)])
    ),
    child: SplashScreen(
        seconds: 3,

        //this is conditional statement for navigation 
        navigateAfterSeconds: (a != null ? introduce()  : login()),
        loadingText: new Text('calculator',
          textAlign: TextAlign.center,
          style: new TextStyle(
            fontSize: 20, fontWeight: FontWeight.w900, fontFamily: 'yasamin',color: Colors.white,
          ),),
        image: new Image.asset('images/logo_logo.png'),
        styleTextUnderTheLoader: new TextStyle()
        photoSize: 100.0,
        onClick: ()=>print("wellcome"),
        loaderColor: Colors.white,
    ),
   ),
 );
 }
} 

标签: flutterauthenticationnavigation

解决方案


如果你想使用数组,我认为有一些最好的方法。而不是做 var a,你可以只使用。

List<dynamic> a = [];

然后在你的 initState 中,因为它不返回任何String值,而是写这个

void initState() {
 super.initState();
   setState(() {

   // Your Sqlite Class
   final vdbhelper = new ValuesDbprovider();
   final dbResult = await vdbhelper.fetchValues();

   // secondary option
   List<dynamic> myData = dbResult.map((e) => e.user_no ).toList();
   a.addAll(myData);

   print("a: $a");
 });

注意:您的代码不清楚,a总是会返回 null 因为不清楚values_list_r 来自哪里。而且您正在执行一个方法vdbhelper.fetchValues();,但没有将其保存到变量中。当然,a总是会返回 null,因为它没有来源


推荐阅读