Home > Net >  I get a null error when I try to run my flutter app after trying to fetch data from a url
I get a null error when I try to run my flutter app after trying to fetch data from a url

Time:05-03

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. 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)

enter image description here

enter image description here


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(),
            )
    );
  }
}```

CodePudding user response:

GET https://jsonplaceholder.typicode.com/photos will return a list of photos.

Replace

var res = await http.post(Uri.parse(url));

with

var res = await http.get(Uri.parse(url));
  • Related