
每當我嘗試從 REST API 獲取資料時,我都會不斷收到錯誤訊息“期望值型別為 'Widget?',但得到一個型別為 'String'”。我的代碼沒有任何問題,但我不斷收到錯誤訊息。
這是從資料庫中獲取專案的函式。
Future<List<Map>> fetchItems() async {
List<Map> items = [];
//get data from API and assign to variable
http.Response response =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
if (response.statusCode == 200) {
//get data from the response
String jsonString = response.body;
items = jsonDecode(jsonString).cast<Map>();
}
return items;
}
這是我的 main.dart 檔案
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: PostList(),
);
}
}
class PostList extends StatelessWidget {
PostList({super.key});
final Future<List<Map>> _futurePosts = HTTPHelper().fetchItems();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Posts"),
),
body: FutureBuilder(
future: _futurePosts,
builder: ((context, snapshot) {
//check for error
if (snapshot.hasError) {
return Center(
child: Text("Some error has occured ${snapshot.error}"));
}
//has data
if (snapshot.hasData) {
List<Map> _posts = snapshot.data!;
return ListView.builder(
itemCount: _posts.length,
itemBuilder: ((context, index) {
Map _thisItem = _posts[index];
return ListTile(
title: _thisItem["title"],
subtitle: _thisItem["body"],
);
}));
}
//display a loader
return Center(child: CircularProgressIndicator());
}),
),
);
}
}
這個錯誤有什么解決辦法嗎?
uj5u.com熱心網友回復:
答案很簡單。您正在將字串值直接分配給標題(期待 Widget)。你可以試試下面的代碼
ListView.builder(
itemCount: _posts.length,
itemBuilder: ((context, index) {
Map _thisItem = _posts[index];
return ListTile(
title: Text(_thisItem["title"].toString()),
subtitle: Text(_thisItem["body"].toString()),
);
}));
如果這不起作用。請告訴我。
uj5u.com熱心網友回復:
ListTile(標題:這里需要小工具,副標題:這里需要小工具,)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/520967.html
標籤:扑镖
上一篇:Dart異步執行順序
