我是Flutter的新手。我遇到了這樣的錯誤,你能幫助我嗎?
我被困在http for json已經5天了,源代碼中的代碼不起作用。 :( L
它說未輸入串列,但當我輸入時,它不接受它。 我不知道問題出在哪一行,但我得到了一個警告,比如。
// 要決議這個JSON資料,請執行。
//
//最終post = postFromJson(jsonString);
import 'dart:convert'。
Post PostFromJson(String str) => Post.fromJson(json.decode(str) );
String postToJson(Post data) => json.encode(data.toJson() )。
class Post{
帖子({
required this.userId,
required this.id。
required this.title。
required this.body。
});
int userId;
int id;
String title。
String body。
factory Post.fromJson(Map<String, dynamic> json) => Post(
userId。json["userId"]。
id: json["id"]。
title: json["title"]。
body: json["body"]。
);
Map<String, dynamic> toJson()=> {
"userId": userId,
"id": id,
"title": 標題。
"body": body。
};
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:json_http_place_holder/post.dart'。
void main() {
runApp(const MyApp())。
}
class MyApp extends StatefulWidget{
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState()。
}
class _MyAppState extends State< MyApp> {
Future getData = Future(() => null) 。
var con = Uri.parse("https://jsonplaceholder.typicode.com/posts") 。
Future<List<Post>> fetchPost() async {
List<Post> result = <Post> [];
final response = await http.get(con)。
if (response.statusCode == 200) {
List listPost = jsonDecode(response.body)。
for (int i = 0; i < listPost.length; i ) {
Post item = Post.fromJson(listPost[i]);
result.add(item);
}
}
return result;
}
@override
void initState() {
// TODO: implement initState
super.initState()。
getData = fetchPost()。
}
@override
Widget build(BuildContext context) {
return MaterialApp(
標題。'Flutter HTTP json'。
主題。ThemeData(
primarySwatch: Colors.blue,
),
首頁。腳手架(
身體。FutureBuilder(
future: getData,
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
孩子。CircularProgressIndicator(),
);
} else if ( snapshot.connectionState == ConnectionState.none) {
return const Center(
孩子。Text("Bir hata meydana geldi") 。
);
} else if (snapshot.connectionState == ConnectionState.done) {
return ListView.separate(itemBuilder: (context,index){
return ListTile(
領導。Icon(Icons.local_post_office)。
標題。Text(snapshot.data[index].title)。
副標題。Text(snapshot.data[index].body)。
);
},separatorBuilder: (context,index)=>Divider(),
itemCount: snapshot.data.lenght,
);
}
//var d =jsonDecode(snapshot.data.body);
return Container()。
},
),
),
);
}
}
uj5u.com熱心網友回復:
你沒有拼好長度。
這個錯誤告訴我們在串列中沒有這樣的方法 lenght
獲得方法的正確拼法是.length
改變
itemCount: snapshot.data.lenght,
to
itemCount: snapshot.data.length。
uj5u.com熱心網友回復:
在你的main.dart中。 FutureBuilder => separatorBuilder =>/p>
itemCount: snapshot.data.lenght,
把itemCount改成:
itemCount: snapshot.data.length,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315505.html
標籤:
上一篇:如何用NestJS建立授權服務?
下一篇:如何點擊svg元素?
