gpt4 book ai didi

dart - 异步调用值首次为NULL,从而在构建MainPage时导致断言错误(窗口小部件脏)

转载 作者:行者123 更新时间:2023-12-03 04:16:42 25 4
gpt4 key购买 nike

我正在开发一个flutter小部件,该小部件需要使用rest调用来加载和更新Text中的数据。异步调用fetchPatientCount从REST资源中获取数据,并在counter方法内部更新setState

作为以下实现的结果,由于build方法调用了两次,因此counter值首次为NULL并导致以下异常,而第二次填充该值。

 flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MainPage(dirty, state: _MainPageState#9e9d8):
flutter: 'package:flutter/src/widgets/text.dart': Failed assertion: line 235 pos 15: 'data != null': is not
flutter: true.

与该问题有关的任何帮助将不胜感激。 enter image description here
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
String counter;

@override
void initState() {
super.initState();
fetchPatientCount().then((val) {
setState(() {
counter = val.count.toString();
});
});
}

@override
Widget build(BuildContext context) {
String text;
if(counter!=null) {
text = counter;
}

return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
Text(text,/* Here text is NULL for the first time */
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}


Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
}

class PatientCount {
int count;
double amount;

PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}

Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";

Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";

String requestBody = '{"consultedOn":' + '16112018' + '}';

http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);

final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);

if (statusCode != 200 || responseBody == null) {
throw new Exception(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}

最佳答案

我解决了自己的问题,使用FutureBuilder解决了问题。
这是下面的完整代码。

class PatientCount {
int count;
double amount;

PatientCount({this.count, this.amount});

PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}

Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";

Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";

String requestBody = '{"consultedOn":' + '16112018' + '}';

http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);

final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);

if (statusCode != 200 || responseBody == null) {
throw new FetchPatientCountException(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}


class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
/*Text(get,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))*/
buildCountWidget()
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}

Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}

Widget buildCountWidget() {
Widget vistitCount = new Center(
child: new FutureBuilder<PatientCount>(
future: fetchPatientCount(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.count.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}

// By default, show a loading spinner
return new CircularProgressIndicator();
},
),
);
return vistitCount;
}
}

关于dart - 异步调用值首次为NULL,从而在构建MainPage时导致断言错误(窗口小部件脏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com