【发布时间】:2021-10-31 14:06:50
【问题描述】:
我正在观看一个视频来实现 listview builder,但遇到了上面提到的错误,我认为这是由于 null 安全性但不知道如何解决它。我正在研究 vscode 并启动 lib\main。 dart 在 Chrome 上调试模式。以下是我的完整代码:
有两个类,即 main.dart 和 note.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:listview/entities/note.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
var notes = <Note>[];
if (response.statusCode == 200) {
var notesJson = jsonDecode(response.body);
for (var noteJson in notesJson) {
notes.add(Note.fromJson(noteJson));
}
}
return notes;
}
@override
Widget build(BuildContext context) {
fetchNotes().then((value) {
_notes.addAll(value);
});
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Listview with Json"),
),
body: ListView.builder(
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32.0, bottom: 32.0, left: 16.0, right: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
_notes[index].title,
style: TextStyle(
fontSize: 22, fontWeight: FontWeight.bold),
),
Text(
_notes[index].text,
style: TextStyle(color: Colors.grey.shade700),
)
],
),
),
);
},
itemCount: _notes.length,
)));
}
}
class Note {
late String title;
late String text;
Note(this.title, this.text);
Note.fromJson(Map<String, dynamic> json) {
title = json['title'];
text = json['text'];
}
}
【问题讨论】:
-
这是我关注的视频的 url:youtu.be/Fo04xk9gIFo 我认为我的错误是由于 null 安全性或 json 占位符 @RavindraS.Patil 的 url
-
查看我的回答希望对你有帮助
标签: flutter dart dart-null-safety flutter-futurebuilder flutter-listview