我无法弄清楚为什么在我确定应该有一个值的同时,将来的构建器中总是得到null回报
//global variables
Map<String,bool> students;
List<String> studentsList ;
List<bool> studentsCheck ;
FutureBuilder(
future: GetInfoFromBackEnd(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.hasData?
CustomScrollView(....some not important widgets here....):CircularProgressIndicator();
},)
Future GetInfoFromBackEnd() async {
students = {
'this info should be taken from backend0':false,
'this info should be taken from backend0':false,
'this info should be taken from backend0':false,
'this info should be taken from backend0':false,
'this info should be taken from backend0':false,
};
studentsList = students.keys;
studentsCheck = students.values;
return students;
}
我对此代码有一种解决方法,但是我需要了解为什么这会令人发指以及发生了什么
答案 0 :(得分:0)
提供了包含您的代码的基本HelloWorld Flutter示例。我为将来增加了一个延迟,以便ProgressIndicator显示两秒钟。像我想要的那样工作:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Map<String, bool> students;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: GetInfoFromBackEnd(),
builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
return snapshot.hasData
? new Text(snapshot.data.toString())
: new CircularProgressIndicator();
}),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Future<Map> GetInfoFromBackEnd() async {
return Future.delayed(Duration(seconds: 2), () {
students = {
'this info should be taken from backend0': false,
'this info should be taken from backend1': false,
'this info should be taken from backend2': false,
'this info should be taken from backend3': false,
'this info should be taken from backend4': false,
};
return students;
});
}
}
答案 1 :(得分:0)
问题不在FutureBuilder或地图中,实际上,当我尝试获取学生Map值和List中的每个键时,它破坏了Future并阻止了它返回Corret值,因此快照中没有null。数据;这是我如何修复它:
studentsList = students.keys.toList();
studentsCheck = students.values.toList();
return students;
P.S。 :错误为type '_CompactIterable<String>' is not a subtype of type 'List<String>'