[英]How to display custom error message instead of the exception in Flutter
我已将 Flutter 应用程序连接到 MySQL。 在我的 PHP 文件中,我编写了一个查询来从 MySQL 检索数据。 如果查询成功执行,数据将返回并能够在我的列表中显示。
但是,如果查询失败(如果我的表中没有所需的列),我只想显示“未找到数据”。 但我得到“错误格式异常”。 如何隐藏此错误格式异常?
_getUsers() async {
var data = await http
.post("http://10.0.2.2/Flutter/count.php", body: {
"dat": count,
});
var jsonData = json.decode(data.body);
return jsonData;
}
我的构建是
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.teal,
),
body: Padding(
padding: const EdgeInsets.all(0.0),
child: Container(
color: Colors.teal,
child: new FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasError) {
return Center(
child: new Text('Error ${snapshot.error}'),
);
}
else {
return Center(
child: Padding(
padding: const EdgeInsets.fromLTRB(56.0, 8.0, 56.0, 8.0),
child: ListView.builder(
itemCount: snapshot.data?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: new Text(
'${snapshot.data[index]["branch"]}',
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
),
),
trailing: new Text(
'${snapshot.data[index]["count(`branch`)".toString()]}',
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
),
),
);
}),
),
);
}
}),
),
),
);
}
}
在使用以下解决方案之前,请确保您获得了 map/json 列表作为响应。 即结构必须类似于:
[
{
'branch': 'abc',
'count(`branch`)' : n //a number
},
{
'branch': 'xyz',
'count(`branch`)' : x //a number
},
]
如果结构与上述不相似,请同时发布 json 结构。
答案代码:
String leadingText = 'No Data Found';
String trailingText = '';
try {
leadingText = '${snapshot.data[index]["branch"]}';
trailingText = '${snapshot.data[index]["count(`branch`)".toString()]}';
} catch (e, s) {
print('Exception while fetching data: $e stacktrace: $s );
}
将字符串用作Text
中的普通字符串数据:
leading: new Text(
leadingText,
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
),
),
trailing: new Text(
trailingText,
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
),
),
这将允许您处理format exception
并返回您的自定义字符串作为响应。 但是,如果出现任何异常,您将获得相同的字符串,因此我建议您以自己的方式处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.