Home > front end >  Unexpected null value in debug console
Unexpected null value in debug console

Time:08-19

I have a flutter code which runs fine, but at the same time it throws Unexpected null value error in debug console. Can someone please help why this is happening.

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

//add this library to get data from the internet
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _jsonString =
      '{ "count": 7, "result": [ { "iconId": 1, "id": 1, "name": "Kitchen", "timestamp": 1586951631 }, { "iconId": 2, "id": 2, "name": "android", "timestamp": 1586951646 }, { "iconId": 3, "id": 3, "name": "mobile", "timestamp": 1586951654 }, { "iconId": 4, "id": 4, "name": "bathroom", "timestamp": 1586951665 }, { "iconId": 5, "id": 5, "name": "parking", "timestamp": 1586974393 }, { "iconId": 6, "id": 6, "name": "theatre", "timestamp": 1586974429 }, { "iconId": 7, "id": 7, "name": "bedroom", "timestamp": 1586974457 } ] }';

  Future<String> _getDataFromWeb() async {
    // http.Response response = await http.get(
    //   Uri.parse("http://localhost/api/Ticket/GetTickets?username=myuser"),
    //   headers: {
    //     'Content-Type': 'application/json',
    //     'Accept': 'application/json'
    //   },
    // );

    // if (response.statusCode == 200) {
    //   // If you are sure that your web service has json string, return it directly
    //   return response.body;
    // } else {
    //   // create a fake response against any stuation that the data couldn't fetch from the web
    //   return _jsonString;
    // }
    return _jsonString;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Your App Title"),
      ),
      body: FutureBuilder<String>(
        future: _getDataFromWeb(),
        builder: (context, snapshot) {
          Map jsonMap = json.decode(snapshot.data!);

          return GridView.builder(
            gridDelegate:
                SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
            itemCount: jsonMap['count'],
            itemBuilder: (BuildContext c, int i) {
              Map resultItem = jsonMap['result'][i];

              return Card(
                child: Center(child: Text("${resultItem['name']}")),
              );
            },
          );
        },
      ),
    );
  }
}

Please review the above code and help me find out the problem. A runtime null is generated from somewhere, and it is throwing repeated errors in console. You can run the above code and see if the problem happens.

CodePudding user response:

Loading future takes some time, you need to await until the data is ready,

builder: (context, snapshot) {
  if(snapshot.hasData){
  Map jsonMap = json.decode(snapshot.data!);
  return GridView.builder(
    gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
    itemCount: jsonMap['count'],
    itemBuilder: (BuildContext c, int i) {
      Map resultItem = jsonMap['result'][i];

      return Card(
        child: Center(child: Text("${resultItem['name']}")),
      );
    },
  );}

  return CircularProgressIndicator();
}

Highly recommend checking this doc example handling error and other states.

  • Related