Home > Mobile >  How to fix 'Unhandled Exception: Null check operator used on a null value' in flutter post
How to fix 'Unhandled Exception: Null check operator used on a null value' in flutter post

Time:09-30

I'm new to flutter. I'm trying to learn about flutter rest api. When I'm trying to post data using fullter api(using http dart package), It shows me this error.

Error Image

I tried to fix it doing some changes to my code, but I still unable to fix it. Here the code that I trying to execute.

  1. Model

     import 'dart:convert';
    
    DataModel dataModelFromJSON(String str) => DataModel.fromJson(jsonDecode(str));
    String dataModelToJson(DataModel data) => json.encode(data.toJson());
    
    class DataModel {
     DataModel(
       {required this.name,
       required this.job,
       required this.id,
       required this.createdAt});
    
       String name;
       String job;
       String id;
       String createdAt;
    
    factory DataModel.fromJson(Map<String, dynamic> json) => DataModel(
       name: json['name'],
       job: json['job'],
       id: json['id'],
       createdAt: json['createdAt']);
    
      Map<String, dynamic> toJson() =>
         {"name": name, "job": job, "id": id, "createdAt": createdAt};
    }
    
  2. main.dart

     import 'package:flutter/material.dart';
     import 'package:http/http.dart' as http;
    
     import 'DataModel.dart';
    
      void main() {
       runApp(
       MaterialApp(
       home: MyHomePage(),
     ),
     );
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    Future<DataModel?> submitData(String name, String job) async {
       var response = await http.post(
       Uri.https('reqres.in', 'api/users'),
       body: {"name": name, "job": job},
       );
       var data = response.body;
       print(data);
    
       if (response.statusCode == 201) {
        String responseString = response.body;
        dataModelFromJSON(responseString);
       } else
        return null;
       }
    
       class _MyHomePageState extends State<MyHomePage> {
          late DataModel _dataModel;
          TextEditingController nameController = TextEditingController();
          TextEditingController jobController = TextEditingController();
    
       @override
       Widget build(BuildContext context) {
         return Scaffold(
          appBar: AppBar(
          title: Center(
           child: Text('HTTP Post'),
           ),
         ),
         body: Container(
           padding: EdgeInsets.all(20.0),
           child: Column(
             children: [
               TextField(
                 decoration: InputDecoration(
                     border: OutlineInputBorder(), hintText: 'Name'),
                 controller: nameController,
               ),
               SizedBox(height: 20.0),
               TextField(
                 decoration: InputDecoration(
                     border: OutlineInputBorder(), hintText: 'Job'),
                 controller: jobController,
               ),
               ElevatedButton(
                 onPressed: () async {
                   String name = nameController.text;
                   String job = jobController.text;
                   DataModel? data = await submitData(name, job);
                   setState(() {
                     _dataModel = data!;
                   });
                 },
                 child: Text("Submit"),
               )
             ],
           ),
         ),
       );
     }
    }
    

I appreciate if somebody can help me to fix this issue.

CodePudding user response:

You are not returning data in your function add return here

 return dataModelFromJSON(responseString);

Now your Function will be like this

  Future<DataModel?> submitData(String name, String job) async {
       var response = await http.post(
       Uri.https('reqres.in', 'api/users'),
       body: {"name": name, "job": job},
       );
       var data = response.body;
       print(data);
    
       if (response.statusCode == 201) {
        String responseString = response.body;
       return dataModelFromJSON(responseString);
       } else
        return null;
       }

CodePudding user response:

Remove ! from this line _dataModel = data!; In your data model you have this

    String responseString = response.body;
    dataModelFromJSON(responseString);
   } else
    return null;
   }

Which will return null if the status code of the request is not 201, which it's doing so using ! To do the null check is what's causing the error.

  • Related