Home > Net >  The body might complete normally, causing 'null' to be returned, but the return type, 
The body might complete normally, causing 'null' to be returned, but the return type, 

Time:12-23

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type. Try adding either a return or a throw statement at the end. AND The argument type 'String' can't be assigned to the parameter type 'Uri'. `

import 'dart:convert';

import 'package:altamazee/models/user_model.dart';
import 'package:http/http.dart' as http;

class AuthService {
  String baseUrl = 'https://shamo-backend.buildwithangga.id/api';

  Future<UserModel> register({
    required String name,
    required String username,
    required String email,
    required String password,
  }) async {
    var url = '$baseUrl/register';
    var headers = {'Content-Type': 'application/json'};
    var body = jsonEncode({
      'name': name,
      'username': username,
      'email': email,
      'password': password,
    });

    var response = await http.post(
      url,
      headers: headers,
      body: body,
    );

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      UserModel user = UserModel.fromJson(data['user']);
      user.token = 'Bearer '   data['access_token'];

      return user;
    }
  }
}

`

This my code pliss helpmeee enter image description here

CodePudding user response:

The first error is because you don't return anything if your http.post request isn't successful. You can fix this by returning something even if the post request fails, such as using Future<UserModel?> as the return type (null if no UserModel is returned), by returning an empty UserModel, or by throwing an error.

The second error is because the first parameter for http.post is a Uri, not a string. Build your Uri according to the example here: http package example.

final url = Uri.https('https://shamo-backend.buildwithangga.id', '/api/register'); 

CodePudding user response:

First error says what if you haven’t get any response due to error!

You only checked for 200 status code. If error happens then this block if(response.statusCode == 200) will not be executed. So, there is nothing to return! You may write like this,

if(response.statusCode == 200)
{
  // your code 
}
return null; //this will execute if error occurs

But doing this will show an error because your return type is, Future<UserModel>. So, change it to Future<UserModel?> will fix the first error!

Second Error This worked previously, but now http needs Uri type instead of String.

Doing like this will fix your error,

var response = await http.post(
      Uri.parse(url),
      headers: headers,
      body: body,
    );

  • Related