[英]I get a null error when I try to run my flutter app after trying to fetch data from a url
I get the error below after modifying my home page on my app to the code as shown below, I get the error in my object_patch.dart file.在将我的应用程序主页修改为如下所示的代码后,我收到以下错误,我在我的 object_patch.dart 文件中收到错误。 I don't know how that can be resolved.
我不知道如何解决。 what could I have done wrong?
我做错了什么?
Exception has occurred.发生异常。 NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: ) (see image)
NoSuchMethodError(NoSuchMethodError:在 null 上调用了方法“[]”。接收方:null 尝试调用:) (见图)
import 'package:awsome_app/drawer.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
//Functions here now
// var myText = "This is a function";
// TextEditingController _nameController = TextEditingController();
var url = "https://jsonplaceholder.typicode.com/photos";
var data;
@override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
fetchData() async {
var res = await http.post(Uri.parse(url));
data = jsonDecode(res.body);
setState(() {});
;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(204, 255, 249, 249),
appBar: AppBar(title: const Text("Welcome to Flutter App")),
body: data != null
? ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index]["title"]),
);
},
itemCount: data.length,
)
: Center(
child: CircularProgressIndicator(),
)
);
}
}```
GET https://jsonplaceholder.typicode.com/photos will return a list of photos. GET https://jsonplaceholder.typicode.com/photos将返回照片列表。
Replace代替
var res = await http.post(Uri.parse(url));
with和
var res = await http.get(Uri.parse(url));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.