NoSuchMethodError was thrown building FutureBuilder

1,625 views
Skip to first unread message

Kristin

unread,
May 17, 2021, 6:01:52 PM5/17/21
to Flutter Development (flutter-dev)
I want to get a JSON object from an api and format the information to screen. So far I've done the below as a practice:
class Home extends StatelessWidget {
   final String accountNum;
   Home(this.accountNum);
   final String apiUrl = "https://jsonplaceholder.typicode.com/todos/";

   Future<Map<String, dynamic>> fetchData() async {
      var result = await http.get(apiUrl+accountNum);
      //print(json.decode(result.body));
      return json.decode(result.body);
   }

   String _meterNum(dynamic account){
      return account['title'];
   }

   @override
   Widget build(BuildContext context) {
      return Scaffold(
         appBar: AppBar(
         title: Text('Account Data'),
       ),
      body: Container(
         child: FutureBuilder<Map<String, dynamic>>(
            future: fetchData(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if(snapshot.hasData){
                     print(_meterNum(snapshot.data[0]));
                      return ListView.builder(
                        padding: EdgeInsets.all(8),
                         itemCount: snapshot.data.length,
                         itemBuilder: (BuildContext context, int index){
                             return
                             Card(
                                 child: Column(
                                     children: <Widget>[
                                          ListTile(
                                              leading: CircleAvatar(
                                                   radius: 30,
                                                       backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
                                                         )
                                                   ],
                                           ),
                                       );
                                 });
                     }else {
                            return Center(child: CircularProgressIndicator());
                      }
              } else {
                      return Text('Error Connecting to API');
                       //return Center(child: CircularProgressIndicator());
              }
         },
     ),
  ),
);
}
}
I have been able to print the jSON object in the "fetchData()" function but cannot in the "FutureBuilder", instead I immediately get an error: 
The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#6cfd6):
The method '[]' was called on null.
Receiver: null
Tried calling: []("title")

How can I fix this?

Kristin

unread,
May 17, 2021, 6:05:02 PM5/17/21
to Flutter Development (flutter-dev)
I forgot to mention the api url is a combination of "https://jsonplaceholder.typicode.com/todos/" plus a number passed from the previous screen: 1,2,...
Like I said, within the fetchData() function I run " print(json.decode(result.body));" and it prints the JSON.

Suzuki Tomohiro

unread,
May 17, 2021, 6:44:52 PM5/17/21
to Kristin, Flutter Development (flutter-dev)
Can you share the stack trace of the error?


--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/214ee47a-82b7-4170-9be0-c73bed86ad46n%40googlegroups.com.

Kristin

unread,
May 17, 2021, 7:28:34 PM5/17/21
to Flutter Development (flutter-dev)
Hey sorry I got confused between the messages being replied to me and on this board.
On line 159 is this "print(_meterNum(snapshot.data[0]));" indicating that snapshot doesn't recieve any data.
In my original code with future: fetchData(), within fetchData I do:  print(json.decode(result.body)); and it prints, let me revert back to that and copy and paste the stack trace for that one sec.

Kristin

unread,
May 17, 2021, 7:30:33 PM5/17/21
to Flutter Development (flutter-dev)
Stach trace with fatchData() in FutureBuilder:

Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 773ms.
W/IInputConnectionWrapper( 9782): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper( 9782): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper( 9782): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper( 9782): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper( 9782): endBatchEdit on inactive InputConnection

======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 112 pixels on the bottom.

The relevant error-causing widget was: 
  Column file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/addaccount.dart:93:20
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.

Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.

The specific RenderFlex in question is: RenderFlex#918a4 relayoutBoundary=up4 OVERFLOWING
...  needs compositing
...  parentData: offset=Offset(36.0, 36.0) (can use size)
...  constraints: BoxConstraints(0.0<=w<=339.4, 0.0<=h<=329.1)
...  size: Size(339.4, 329.1)
...  direction: vertical
...  mainAxisAlignment: center
...  mainAxisSize: max
...  crossAxisAlignment: center
...  verticalDirection: down
◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
====================================================================================================

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#5f834):
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

The relevant error-causing widget was: 
  FutureBuilder<Map<String, dynamic>> file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/home.dart:156:16
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      Home.build.<anonymous closure> (package:BWS_App/screens/home.dart:159:42)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
...
====================================================================================================
I/flutter ( 9782): {userId: 1, id: 1, title: delectus aut autem, completed: false}

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#5f834):
The method '[]' was called on null.
Receiver: null
Tried calling: []("title")

The relevant error-causing widget was: 
  FutureBuilder<Map<String, dynamic>> file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/home.dart:156:16
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      Home._meterNum (package:BWS_App/screens/home.dart:91:19)
#2      Home.build.<anonymous closure> (package:BWS_App/screens/home.dart:159:19)
#3      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
====================================================================================================


Suzuki Tomohiro

unread,
May 17, 2021, 7:33:33 PM5/17/21
to Kristin, Flutter Development (flutter-dev)
In that line, “snapshot.data” is null. Use the debugger and breakpoint to confirm that.

Kristin

unread,
May 17, 2021, 7:41:44 PM5/17/21
to Flutter Development (flutter-dev)
Ok so I out the breakpoint on lines:
child: FutureBuilder<Map<String, dynamic>>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(_meterNum(snapshot.data[0]));

And the stack trace remains the same:
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 688ms.
W/IInputConnectionWrapper( 9782): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper( 9782): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper( 9782): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper( 9782): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper( 9782): endBatchEdit on inactive InputConnection

======== Exception caught by rendering library =====================================================
The following assertion was thrown during layout:
A RenderFlex overflowed by 112 pixels on the bottom.

The relevant error-causing widget was: 
  Column file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/addaccount.dart:93:20
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.

Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.

The specific RenderFlex in question is: RenderFlex#9fa8e relayoutBoundary=up4 OVERFLOWING
...  needs compositing
...  parentData: offset=Offset(36.0, 36.0) (can use size)
...  constraints: BoxConstraints(0.0<=w<=339.4, 0.0<=h<=329.1)
...  size: Size(339.4, 329.1)
...  direction: vertical
...  mainAxisAlignment: center
...  mainAxisSize: max
...  crossAxisAlignment: center
...  verticalDirection: down
◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
====================================================================================================

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#2ff46):
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

The relevant error-causing widget was: 
  FutureBuilder<Map<String, dynamic>> file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/home.dart:156:16
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      Home.build.<anonymous closure> (package:BWS_App/screens/home.dart:159:42)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
...
====================================================================================================
I/flutter ( 9782): {userId: 1, id: 1, title: delectus aut autem, completed: false}

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#2ff46):
The method '[]' was called on null.
Receiver: null
Tried calling: []("title")

The relevant error-causing widget was: 
  FutureBuilder<Map<String, dynamic>> file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/home.dart:156:16
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      Home._meterNum (package:BWS_App/screens/home.dart:91:19)
#2      Home.build.<anonymous closure> (package:BWS_App/screens/home.dart:159:19)
#3      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:751:55)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
====================================================================================================


Suzuki Tomohiro

unread,
May 17, 2021, 7:54:33 PM5/17/21
to Kristin, Flutter Development (flutter-dev)
Breakpoints do not fix a problem. It helps you to understand the problem. Do you now know why your program throws NoSuchMethodErrors?

Kristin

unread,
May 17, 2021, 7:59:38 PM5/17/21
to Flutter Development (flutter-dev)
I'm sorry this environment is very new to me 😅
I can see that the FutureBuilder is the problem but beyond that I'm not sure how to remedy this. 

Suzuki Tomohiro

unread,
May 17, 2021, 9:01:23 PM5/17/21
to Kristin, Flutter Development (flutter-dev)
Do you know why your program throws NoSuchMethodErrors?

Kristin

unread,
May 17, 2021, 11:45:53 PM5/17/21
to Flutter Development (flutter-dev)
Hey sorry I had signed off for the day but came back because I really want to solve this,
Do I need to make the FutureBuilder method? I thought that was something that came in the package?

Suzuki Tomohiro

unread,
May 17, 2021, 11:49:56 PM5/17/21
to Kristin, Flutter Development (flutter-dev)
Do you know the root cause of the problem now?

Kristin

unread,
May 17, 2021, 11:52:57 PM5/17/21
to Flutter Development (flutter-dev)
I think it's the FutureBuilder method but if I'm being honest I'm a little lost 😅

Kristin

unread,
May 18, 2021, 12:05:03 AM5/18/21
to Flutter Development (flutter-dev)
Is the reason because snapshot is null?

Suzuki Tomohiro

unread,
May 18, 2021, 12:06:58 AM5/18/21
to Kristin, Flutter Development (flutter-dev)
Good. Can you investigate why the variable at home.dart line 159 is null?

This is about the error below:

The following NoSuchMethodError was thrown building FutureBuilder<Map<String, dynamic>>(dirty, state: _FutureBuilderState<Map<String, dynamic>>#2ff46):
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

The relevant error-causing widget was: 
  FutureBuilder<Map<String, dynamic>> file:///C:/Users/kvernon/IdeaProjects/BWS_App/lib/screens/home.dart:156:16
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      Home.build.<anonymous closure> (package:BWS_App/screens/home.dart:159:42)

Kristin

unread,
May 18, 2021, 12:22:51 AM5/18/21
to Flutter Development (flutter-dev)
I guess what I'm not undersatnding is how is the data passed from the fetchData function to snapshot

Suzuki Tomohiro

unread,
May 18, 2021, 12:28:01 AM5/18/21
to Kristin, Flutter Development (flutter-dev)
The snapshot variable is never null. Snapshot.data may be null. Can you investigate when/why the data field becomes null?

I agree that you need to pay attention to fetchData.

Kristin

unread,
May 18, 2021, 4:29:07 PM5/18/21
to Flutter Development (flutter-dev)
HEY THANK YOU I GOT IT!!!!
You helped me wind down the issue and I realized now I was parsing the json object wrong and snapshot was the issue! So instead of  _meterNum(snapshot.data[0]) it was _meterNum(snapshot.data) and this works!!

Suzuki Tomohiro

unread,
May 18, 2021, 4:54:21 PM5/18/21
to Kristin, Flutter Development (flutter-dev)
You’re welcome. Glad to hear you sorted it out.

Reply all
Reply to author
Forward
0 new messages