flutter - 为什么空变量在条件下分配不为空?
问题描述
我有一个条件语句让登录用户在启动屏幕后保持抖动,当列表为空时导航到 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,
),
),
);
}
}
解决方案
如果你想使用数组,我认为有一些最好的方法。而不是做 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,因为它没有来源
推荐阅读
- python - Pandas : filter the rows based on a column containing lists
- google-chrome - 如何删除 PWA 图标上的 Chrome Android 徽章
- ios - 必须从 Xcode 11.2 中的主线程使用获取警告,并且应用程序崩溃,在 Xcode 10.2 中未收到警告
- javascript - 如何在 mvc 上的简单 js 中创建中间件并在内核中定义
- java - 如何在java中返回过滤后的Hashmap的值?
- c - 在 MAC 上的 C 文件中编译具有 GObject 相关库的代码时 gcc 抛出错误
- python - 打开 ROOT NTuple 进行机器学习的最快、最节省内存的方法是什么?
- unit-testing - 如何模拟 this.$refs.form.resetValidation()?
- python - 迭代字典会抛出 TypeError:列表索引必须是整数或切片,而不是元组
- android - 如何在谷歌地图上获取图像的中心坐标