Home > OS >  POST Request flutter return null
POST Request flutter return null

Time:11-26

suppose there are 3 integer value (red, green, blue) and the result in String which the prediction after execute the value. I think the problem is the api cannot read String that I had declare in flutter. I have a very difficult to recognise and change the data type in flutter, since controller cannot read integer.

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  RgbModel? _rgbcolor;

  final TextEditingController rController = TextEditingController();
  final TextEditingController gController = TextEditingController();
  final TextEditingController bController = TextEditingController();

  Future<RgbModel> createRGB(String red, String green, String blue) async {
    final response = await http.post(Uri.parse('http://10.0.2.2:8000/predict/'),
        body: {"red": red, "green": green, "blue": blue});
    if (response.statusCode == 200 || response.statusCode == 422) {
      final String responseBody = response.body;
      return rgbModelJson(responseBody);
    } else {
      throw Exception("Failed");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
              TextField(
                controller: rController,
                decoration: InputDecoration(hintText: 'Enter Value R'),
              ),
              TextField(
                controller: gController,
                decoration: InputDecoration(hintText: 'Enter Value G'),
              ),
              TextField(
                controller: bController,
                decoration: InputDecoration(hintText: 'Enter Value G'),
              ),
              SizedBox(
                height: 10,
              ),
              _rgbcolor == null
                  ? Container()
                  : Text('The prediction ${_rgbcolor?.color}'),
              ElevatedButton(
                  onPressed: () async {
                    var rd = rController.text;
                    var grn = gController.text;
                    var bl = bController.text;

                    final RgbModel? usercolor = await createRGB(rd, grn, bl);

                    setState(() {
                      _rgbcolor = usercolor;
                    });
                  },
                  child: Text('Post'))
            ],
          ),
        ),
      ),
    );
  }
}

rgbModel.dart

import 'dart:convert';

RgbModel rgbModelJson(String str) => RgbModel.fromJson(json.decode(str));

String userModelToJson(RgbModel data) => json.encode(data.toJson());

class RgbModel {
  String? color;
  String? red;
  String? green;
  String? blue;

  RgbModel({
    this.color,
    this.red,
    this.green,
    this.blue,
  });

  factory RgbModel.fromJson(Map<String, dynamic> json) => RgbModel(
        color: json["color"],
        red: json["red"].toString(),
        green: json["green"].toString(),
        blue: json["blue"].toString(),
      );

  Map<String, dynamic> toJson() => {
        "color": color,
        "red": red,
        "green": green,
        "blue": blue,
      };
}

in debug console vscode dont give a error conclusion of my code.

Unfortunately,the flutter return null

Unfortunately,the flutter return null

I use FastAPI, this is the API response give the value that I want after execute the value red, green, blue. The return was rgb value ("black")

I use FastAPI, this is the API response after execute the value re,green,blue. The return was rgb value ("black")

CodePudding user response:

In createRGB() function, you try parse the string to int

CodePudding user response:

Your API return a data like {"prediction" : "black"}

Your way to handle it is call rgbModelJson(responseBody)

The function will call this

factory RgbModel.fromJson(Map<String, dynamic> json) => RgbModel(
        color: json["color"],
        red: json["red"].toString(),
        green: json["green"].toString(),
        blue: json["blue"].toString(),
      );

In this function, it try to find the keys color, red, green and blue, while there is the only the prediction. Therefore, json["color"] ,json["red"] ,json["green"] ,json["blue"] will get null. It means that you use the returning data to create a object but all its parameter are null.

When you try to get Text('The prediction ${_rgbcolor?.color}') in screen, it will always null.

I have two ways to solve it:

The first one is change function like:

factory RgbModel.fromJson(Map<String, dynamic> json) => RgbModel(
        color: json["prediction"],
        red: json["red"].toString(),
        green: json["green"].toString(),
        blue: json["blue"].toString(),
      );

but when your try to get like _rgbcolor.red, it will still be null. In case you need the value, you may use the value from textEditingController to change it.

The second one is change your API return format like

{
    "color" : "black",
    "red" : 0,
    "green" : 0,
    "blue" : 0,
}
  • Related