HALIM
HALIM

Reputation: 75

Flutter Set AppBar Title Using JSON Showing Error

I have an application made using flutter, but it displays an error showing that method [] returns null.

I really do not understand where the location lies. and the exception thrown in the first line leads to when I set the title in the AppBar.

I/flutter ( 6601): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 6601): The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePageState#b5688):
I/flutter ( 6601): The method '[]' was called on null.
I/flutter ( 6601): Receiver: null
I/flutter ( 6601): Tried calling: []("title")
I/flutter ( 6601):
I/flutter ( 6601): The relevant error-causing widget was:
I/flutter ( 6601):   HomePage                                                                                   package:blogger/main.dart:13
I/flutter ( 6601):
I/flutter ( 6601): When the exception was thrown, this was the stack:
I/flutter ( 6601): #0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:53:5)
I/flutter ( 6601): #1      _HomePageState.build                                                                 package:blogger/main.dart:47
I/flutter ( 6601): #2      StatefulElement.build                                                                package:flutter/…/widgets/framework.dart:4334
I/flutter ( 6601): #3      ComponentElement.performRebuild                                                      package:flutter/…/widgets/framework.dart:4223
I/flutter ( 6601): #4      Element.rebuild                                                                      package:flutter/…/widgets/framework.dart:3947
I/flutter ( 6601): #5      ComponentElement._firstBuild                                                         package:flutter/…/widgets/framework.dart:4206
I/flutter ( 6601): #6      StatefulElement._firstBuild                                                          package:flutter/…/widgets/framework.dart:4381
I/flutter ( 6601): #7      ComponentElement.mount                                                               package:flutter/…/widgets/framework.dart:4201
I/flutter ( 6601): #8      Element.inflateWidget 

.....

I/flutter ( 6601): #329    RenderObjectToWidgetAdapter.attachToRenderTree                                       package:flutter/…/widgets/binding.dart:941
I/flutter ( 6601): #330    WidgetsBinding.attachRootWidget                                                      package:flutter/…/widgets/binding.dart:819
I/flutter ( 6601): #331    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>                          package:flutter/…/widgets/binding.dart:804
I/flutter ( 6601): #340    _Timer._runTimers  (dart:isolate-patch/timer_impl.dart:384:19)
I/flutter ( 6601): #341    _Timer._handleMessage  (dart:isolate-patch/timer_impl.dart:418:5)
I/flutter ( 6601): #342    _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:174:12)
I/flutter ( 6601): (elided 8 frames from package dart:async and package dart:async-patch)
I/flutter ( 6601):
I/flutter ( 6601): ════════════════════════════════════════════════════════════════════════════════════════════════════

The error only appears when I change the title of AppBar by retrieving content from json. and when I set it directly like this, then the error does not appear. in the sense that there is no error here.

 @override
  Widget build(BuildContext context) {
    return Scaffold (
      appBar: AppBar(
        title: Text("My Title"),
      ),
    );
  }

below is the whole of the program code I'm working on.

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

import 'dart:async';
import 'dart:convert';

void main () {
  runApp(MaterialApp(
    title: "Blogger App",
    theme: new ThemeData(
      primarySwatch: Colors.yellow
    ),
    home : HomePage(),
  ));
}

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

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

class _HomePageState extends State<HomePage> {

  Map data, feed;

  Future getData() async {
    http.Response response = await http.get("https://www.haliminfo.com/feeds/posts/summary/?max-results=5&alt=json");
    data = json.decode(response.body);
    setState(() {
      feed = data['feed']; 
    });
  }

  @override
  void initState() { 
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold (
      appBar: AppBar(
        title: Text(feed['title']['\$t'].toString()),
      ),
    );
  }
}

then how so that when I change the title on AppBar using JSON that I took from the internet there is no error?

thank you

Upvotes: 1

Views: 518

Answers (1)

Yogesh Sharma
Yogesh Sharma

Reputation: 74

Calling an API call is an async process(which can take some time to fetch the JSON from the page), as your 'feed' object is null at the time of the creation of Activity Exception will be thrown.

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

import 'dart:async';
import 'dart:convert';

void main () {
  runApp(MaterialApp(
    title: "Blogger App",
    theme: new ThemeData(
      primarySwatch: Colors.yellow
    ),
    home : HomePage(),
  ));
}

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

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

class _HomePageState extends State<HomePage> {

  Map data, feed;
  String appTitle = '';


  Future getData() async {
    http.Response response = await http.get("https://www.haliminfo.com/feeds/posts/summary/?max-results=5&alt=json");
    data = json.decode(response.body);
    setState(() {
      feed = data['feed']; 
      appTitle = feed['title']['\$t'].toString();
    });
  }

  @override
  void initState() { 
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold (
      appBar: AppBar(
        title: Text(appTitle),
      ),
    );
  }
}

Upvotes: 2

Related Questions