Dart报错:'int'类型无法分配给'Widget'列表类型的问题求助
错误解决:The element type 'int' can't be assigned to the list type 'Widget'
错误根源
Row的children参数要求是List<Widget>类型,但你在for循环里直接写了变量赋值代码:i = i + periode_Lecture[Licture_begin.indexOf(i)]——这行代码执行后返回的是int数值,并非Widget组件,类型不匹配导致了报错。你尝试转Int()没用,因为本质问题是这里不能放非Widget类型的代码,即使转了还是int,不符合要求。
解决方法
变量赋值、逻辑计算这类代码不能直接放在Widget列表里,必须移到UI构建逻辑之外处理,以下是两种可行的修正方案:
方案1:提前处理变量更新
如果是在StatefulWidget的build方法中,先在构建Row之前完成变量i的更新:
// List used List<int> Licture_begin = <int>[8, 10, 14]; List<int> periode_Lecture = <int>[2, 3, 1]; @override Widget build(BuildContext context) { // 先在UI构建前处理变量更新逻辑 if (Licture_begin.contains(i)) { i += periode_Lecture[Licture_begin.indexOf(i)]; } return Row( children: [ Expanded( flex: periode_Lecture[Licture_begin.indexOf(i)], child: Column(children: const [ Text( "المادة", style: TextStyle(fontSize: 10), ), Text( "القاعة-اسم الدكتور", style: TextStyle(fontSize: 10), ) ]), ), // 若不需要额外UI组件,直接删除原for循环;若需要则添加Widget类型元素 ], ); }
方案2:在Widget生成逻辑中处理变量更新
如果你的目标是循环生成Expanded组件同时更新i,可通过列表生成器处理:
// List used List<int> Licture_begin = <int>[8, 10, 14]; List<int> periode_Lecture = <int>[2, 3, 1]; Row( children: [ ...List.generate(periode_Lecture.length, (index) { // 在生成Widget的同时处理变量更新 i += periode_Lecture[index]; return Expanded( flex: periode_Lecture[index], child: Column(children: const [ Text( "المادة", style: TextStyle(fontSize: 10), ), Text( "القاعة-اسم الدكتور", style: TextStyle(fontSize: 10), ) ]), ); }), ], )
核心原则:children列表中的每一项必须是Widget类型,所有非UI逻辑代码要放在Widget列表之外处理。
内容的提问来源于stack exchange,提问作者Bavli Badry
相关产品推荐
相关产品推荐

