2021年4月24日星期六

Error in Flutter: Unhandled Exception: NoSuchMethodError: The method 'add' was called on null

I'm new to flutter and I'm trying to save the data via SharedPreferences from the TextField. I have four TextField where user can enter data and submit that data through the Add to Cart Button as shown below:

This is the main screen

My problem is that, whenever user inputted the data, clicks the Add to Cart Button and then clicks Show Cart Button, it just generate white screen from my second screen. While checking the Debug Console, I noticed the error. When I click Add to Cart Button It says:

E/flutter (29227): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled   Exception: NoSuchMethodError: The method 'add' was called on null.  E/flutter (29227): Receiver: null  E/flutter (29227): Tried calling: add("{\"brand\":\"Nike\",\"size\":\"M\",\"quantity\":\"5\",\"color\":\"blue\"}")  E/flutter (29227): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)  E/flutter (29227): #1      HomePageState.saveData  package:shopping_cart/main.dart:133  E/flutter (29227): <asynchronous suspension>  E/flutter (29227):  

So I'm assuming that the error is in my saveData function:

saveData() async {      final Map<String, String> item= Map<String, String>();      item['brand'] = fstcontroller.text;      item['size'] = sndcontroller.text;      item['quantity'] = trdcontroller.text;      item['color'] = fthcontroller.text;        SharedPreferences prefs = await SharedPreferences.getInstance();      var cart = prefs.getStringList("cart");      cart.add(jsonEncode(item));      prefs.setStringList("cart", cart);    }  

Then, whenever I click the Show Cart Button, it only shows white screen and also throws an error:

E/flutter (29227): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled   Exception: NoSuchMethodError: The method 'forEach' was called on null.  E/flutter (29227): Receiver: null  E/flutter (29227): Tried calling: forEach(Closure: (String) => Null)  E/flutter (29227): #0      Object.noSuchMethod (dart:core- patch/object_patch.dart:54:5)  E/flutter (29227): #1      DynamicList.getUser.<anonymous closure>  package:shopping_cart/main.dart:156  E/flutter (29227): #2      State.setState  package:flutter/…/widgets/framework.dart:1089  E/flutter (29227): #3      DynamicList.getUser  package:shopping_cart/main.dart:155  E/flutter (29227): <asynchronous suspension>  E/flutter (29227):  

Here's the code for the Second Screen:

class SecondScreen extends StatefulWidget {    @override    State createState() => new DynamicList();  }    class DynamicList extends State<SecondScreen> {    List<Map<String, String>> listItems= [];      @override    void initState() {      super.initState();      getUser();    }      getUser() async {      SharedPreferences prefs = await SharedPreferences.getInstance();      final cart = prefs.getStringList("cart");      setState(() {        cart.forEach((item) {          listItems.add(jsonDecode(item));        });      });    }      @override    Widget build(BuildContext context) {       return new Scaffold(        body: Column(          children: <Widget>[            Expanded(              child: ListView.builder(                  itemCount: dataLists.length, itemBuilder: buildList),            )          ],        ),      );    }      Widget buildList(BuildContext context, int index) {      return Container(        margin: EdgeInsets.all(4),        decoration: BoxDecoration(            border: Border.all(              color: Colors.blueAccent,              width: 2,            ),            borderRadius: BorderRadius.circular(5)),        child: ListTile(          title: Text(listItems[index]['brand']),        ),      );    }  }  
https://stackoverflow.com/questions/67249663/error-in-flutter-unhandled-exception-nosuchmethoderror-the-method-add-was-c April 25, 2021 at 12:04PM

没有评论:

发表评论