1

I was follwing a video to implement listview builder but got an error mentioned above, I think its due to null safety but don't know how to solve it.I am working on vscode and Launching lib\main.dart on Chrome in debug mode.Following is my complete code:
There are two classes i.e. main.dart and 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'];
  }
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
Ali Punjabi
  • 452
  • 4
  • 19

1 Answers1

0

Try Below code your problem has been solved

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);
  Future<List<dynamic>> getInfoData() async {
    String url = 'https://jsonplaceholder.typicode.com/posts';
    var response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: FutureBuilder<List<dynamic>>(
            future: getInfoData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      var id = snapshot.data![index]['id'];
                      var userid = snapshot.data![index]['userId'];
                      var title = snapshot.data![index]['title'];
                      var body = snapshot.data![index]['body'];

                      return Card(
                        shape: RoundedRectangleBorder(
                          side: BorderSide(
                            color: Colors.green.shade300,
                          ),
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        child: ListTile(
                          leading: Text(id.toString()),
                          title: Text(title),
                          subtitle: Text(body),
                          trailing: Text(userid.toString()),
                        ),
                      );
                    },
                  ),
                );
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

Result of your screen -> Screenshot

Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40