Rudransh Singh Mahra
Rudransh Singh Mahra

Reputation: 115

The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Unable to Fix this Issue

Was watching some flutter tutorials on youtube and practising making some applications using flutter. The same code works great on the tutors while he runs the code but I am facing this error i.e The method '[]' can't be unconditionally invoked because the receiver can be 'null'. I am attaching my code. Tried adding a null check operator also but didn't work.The error occurs at line 55 that is title: Text(myData[index]['body'])

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
  }

  Future getData() async {
    http.Response response = await http
        .get(Uri.parse("https://jsonplaceholder.typicode.com/posts/"));
    if (response.statusCode == HttpStatus.ok) {
      var result = jsonDecode(response.body);
      return result;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WIFI CONNECTIVITY"),
      ),
      body: FutureBuilder(
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var myData = snapshot.data;
            return ListView.builder(
              itemBuilder: (context, index) => ListTile(
                title: Text(myData[index]['body']),
              ),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(
                color: Colors.black,
              ),
            );
          }
        },
      ),
    );
  }
}

Upvotes: 1

Views: 412

Answers (2)

Vettiyanakan
Vettiyanakan

Reputation: 8486

With FutureBuilder

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future getData() async {
    var response = await http
        .get(Uri.parse("https://jsonplaceholder.typicode.com/posts/"));
    if (response.statusCode == 200) {
      var result = jsonDecode(response.body);
      return result;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WIFI CONNECTIVITY"),
      ),
      body: FutureBuilder(
        future: getData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var mydata = snapshot.data as List;
            return ListView.builder(itemBuilder: (context, index) {
              return Container(
                decoration: BoxDecoration(border: Border.all()),
                child: Text(mydata[index]['body']),
              );
            });
          } else {
            return const Center(
              child: CircularProgressIndicator(
                color: Colors.black,
              ),
            );
          }
        },
      ),
    );
  }
}

Upvotes: 1

Rudransh Singh Mahra
Rudransh Singh Mahra

Reputation: 115

I could not find the fix but I have rewritten the code in a different way here is the code ...

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  var _postJson = [];

  final url = "https://jsonplaceholder.typicode.com/posts/";

  void fetchPost() async {
    try {
      final respone = await http.get(Uri.parse(url));
      final jsonData = jsonDecode(respone.body) as List;

      setState(() {
        _postJson = jsonData;
      });
    } catch (err) {
      print(err);
    }
  }

  @override
  void initState() {
    super.initState();
    fetchPost();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WIFI CONNECTIVITY"),
      ),
      body: ListView.builder(
        itemCount: _postJson.length,
        itemBuilder: (context, index) {
          final post = _postJson[index];
          return ListTile(
            leading: Text("Title: ${post["title"]}"),
          );
        },
      ),
    );
  }
}

Upvotes: 1

Related Questions