gpt4 book ai didi

flutter - JSON 文件未在 Flutter 上加载

转载 作者:行者123 更新时间:2023-12-03 04:26:13 24 4
gpt4 key购买 nike

我是 Flutter 的新手,目前我的 JSON 文件内容无法填充到我的模拟器中。它没有显示错误,但没有显示。如果我将内容直接包含在我的代码块中,它就可以正常工作。我无法发现问题。

以下是我的代码:

main.dart 代码

import 'package:emailapp/messagelist.dart';
import 'package:flutter/material.dart';


void main() => runApp(EmailApp());

class EmailApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(

primarySwatch: Colors.green
),
home: MessageList(title: 'Muss Mailer APP'),
);
}
}

消息列表.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MessageList extends StatefulWidget{

final String title;

const MessageList({Key key, this.title}) : super(key: key);

@override
State<StatefulWidget> createState()=>_MessageListState();
}

class _MessageListState extends State<MessageList>{
var messages=const [];

Future loadMessageList() async{
var content=await rootBundle.loadString('data/message.json');
print(content);
var collection=json.decode(content);

setState(() {
messages=collection;
});
}
void initstate() {
loadMessageList();
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),

body: ListView.separated(
separatorBuilder: (context,index)=>Divider(),

itemCount: messages.length,

itemBuilder: (BuildContext context, int index){
var message=messages[index];

return ListTile(
isThreeLine: true,
leading: CircleAvatar( child: Text('AJ'),),
title: Text(message['subject']),
subtitle: Text(message['body'],maxLines: 2, overflow: TextOverflow.ellipsis,),

) ;
},
),


);
}

}

消息.json
   [ {
"subject":"My First Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

},
{
"subject":"My Second Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

},
{
"subject":"My Third Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

},
{
"subject":"My Fourth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

},
{
"subject":"My Fifth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

},
{
"subject":"My Sixth Message",
"body":"Hello Form the other side of life fellas.. and happy to meet you guys"

}]

发布规范.yaml
  assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
- data/message.json

最佳答案

这只是一个拼写错误。这不是 initstate .其initState ( S 是大写字母)。

void initState() {
loadMessageList();
super.initState();
}

关于flutter - JSON 文件未在 Flutter 上加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613709/

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