期望值类型为"int",但在 Flutter 中获得了类型为"字符串"的值之一



我一直在做一个报价应用程序,从rest api获取数据,并在屏幕中央按下一个按钮随机显示每个报价。但不能完全正确

我已经做了一个方法来获取json数据,这是fetchQuotesData(),它在QuotesData中存储未处理的json。随后将其转换为QuotesList列表。

class _MyAppState extends State<MyApp> {
List QuotesList = [];
var _data;
var c;
final url = "https://type.fit/api/quotes";
fetchQuoteData() async {
Response response = await get(Uri.parse(url));
final QuotesData = jsonDecode(response.body);
setState(() {
QuotesList = QuotesData;
});
}
@override
void initState() {
fetchQuoteData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/pic/image4.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.6), BlendMode.darken)
),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Center(
// Use future builder and DefaultAssetBundle to load the local JSON file
child: FutureBuilder(
future: fetchQuoteData(),
builder: (context, snapshot) {
_data = snapshot.data.toString();
var range = new Random();
c = range.nextInt(_data.length);
return Ui_Card(c);
},
),
),
bottomNavigationBar: BottomAppBar(
color: Colors.indigo.shade900,
child: Container(
margin: const EdgeInsets.only(left: 40.0,right: 40.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
IconButton(
tooltip:'Random Quotes',
icon: Icon(Icons.format_quote_outlined) ,
iconSize: 40,
color: Colors.white,
onPressed: (){
HapticFeedback.heavyImpact();
setState(() {
});
},
),
],
),
),
),
),
);
}
Widget Ui_Card(index){
return new Container(
child:  Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(25.0),
child: Text(_data[c]['text'],
style: TextStyle(
fontWeight: FontWeight.w300,
fontSize: 22.0,
color: Colors.white,
fontFamily: 'Raleway-Italic',
fontStyle: FontStyle.italic,),
textScaleFactor: 2.0,)
),
Text(_data[c]['author'],
style:TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
fontFamily: 'Raleway-Bold',
fontSize: 18.0
),
textAlign: TextAlign.left,
),
],
),
),
);
}
}

我怀疑在构建器或快照数据中存在一些错误,但不确定我在哪里卡住

正如对你的问题的评论所提到的,Dart是一种强类型语言。当你使用"var"时,你依赖于类型推断来找出你想要的变量类型。我使用Dart只有一年左右的时间,但根据我的经验,我从来没有尝试过使用"var",因为它可能导致更难调试的错误消息。此外,如果你设置变量类型,linter似乎更善于发现类型不匹配。

var _data;
...
_data = snapshot.data.toString();

上面设置_data为String

child: Text(_data[c]['text'],

在这里,您试图访问它作为其他东西-可能是List<Map<String,String>>Map<int, Map<String,String>>

我的直觉是你的错误信息来自['text']。也许_data的推断类型可以接受一个二维int型索引。Dart字符串的字符可以用int索引访问-即字符串[0]是第一个字符,但它返回一个int,而int不是一个索引类型AFAIK,所以我不知道Dart是怎么处理你的第二个索引维度,想要一个int。我怀疑如果你把它改为int -即_data[0][0],你会得到一个不同的错误信息。

尝试将_data定义为您想要的类型,然后查看linter是否在源代码中显示错误,或者您得到一个更具描述性的错误消息。

相关内容

最新更新