【发布时间】:2021-11-23 17:48:56
【问题描述】:
所以我有这段代码可以正确地从资产中加载图像:
ClipRRect getUserCard(int index) {
double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;
return ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Stack(
children: [
//IMAGE (and Name Overlay)
Container(
width: screenWidth,
height: screenHeight,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(lstUsers[index]["imageUrl"][0]),
fit: BoxFit.cover),
),
//NAME OVERLAY
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
//NAME AND AGE
Container(
//alignment: Alignment.center,
height: 80,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.6),
//borderRadius: BorderRadius.circular(15),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
lstUsers[index]["name"] + ", ",
style: const TextStyle(
color: Colors.white,
fontSize: 24,
),
textAlign: TextAlign.center,
),
Text(
lstUsers[index]["age"],
style: const TextStyle(
color: Colors.white,
fontSize: 20,
),
textAlign: TextAlign.center,
),
],
),
Text(
lstUsers[index]["profession"],
style: const TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontSize: 18,
),
textAlign: TextAlign.center,
),
],
),
),
const Divider(),
//SWIPE BUTTONS
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
FloatingActionButton(
child: const Icon(
Icons.close_outlined,
color: Colors.black,
size: 32,
),
backgroundColor: Colors.white,
onPressed: () {
setState(() {
cardController.triggerLeft();
});
},
),
const SizedBox(
width: 25,
),
FloatingActionButton(
child: const Icon(
Icons.favorite_border_outlined,
color: Colors.black,
size: 32,
),
backgroundColor: Colors.white,
onPressed: () {
setState(() {
cardController.triggerRight();
});
},
),
]),
const Divider(),
],
),
//),
),
// ),
],
),
);
}
但是,这会导致应用每隔几分钟就崩溃一次。谷歌搜索后我意识到这是因为我在主线程中加载图像。加载图像的正确方法是什么。我需要在这里使用 async / Future 吗?如果有,怎么做?
List lstUsers = [
{
"id": "p1",
"name": "John Doe",
"age": "44",
"imageUrl": [
"assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
"assets/images/anastasia-vityukova-unsplash.png",
],
"profession": "Financial Consultant"
},
{
"id": "p2",
"name": "John Doe 2",
"age": "42",
"imageUrl": [
"assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
"assets/images/good-faces-hiba-unsplash.jpg",
],
"profession": "Financial Consultant"
}
];
编辑:直到我只使用一个图片网址,它才崩溃;这意味着图像 url 就像其他属性一样只是另一个键。现在我已经包含了多张图片,它崩溃了。
【问题讨论】:
-
您真的阅读过以下文档吗? Adding assets and images 和 [显示来自互联网的图像](flutter.dev/docs/cookbook/images/network-image)?另外:您的图片在哪里?
-
你能包含来自
lsUsers的样本数据吗? -
我已经添加了代码。图像位于资产文件夹中。 lstUsers 作为数据(列表)存储在普通数据文件中。
-
当您的应用程序崩溃时,您能否添加您的日志,正如我从您的帖子中看到的那样,图像正在加载但应用程序崩溃了?查看日志有助于发现真正的问题。
标签: image flutter dart asynchronous