0

I got an error while using Flutter to create a screen that shows the status of a user. Null safety error, but I don't know the solution. The following error message occurred while implementing the process to display the received data of API on the screen.

Error message

The following _CastError was thrown building Consumer<Status>(dirty, dependencies: [_InheritedProviderScope<Status?>]):
Null check operator used on a null value

The relevant error-causing widget was: 
  Consumer<Status> Consumer:file:///Users/username/StudioProjects/app_name/lib/screens/user_status.dart:55:14

(services/user_status.dart)

import 'package:flutter/material.dart';
import 'package:delivery_kun/models/user_status.dart';
import 'package:dio/dio.dart' as Dio;
import 'package:intl/intl.dart';
import 'dio.dart';

class Status extends ChangeNotifier {
  UserStatus? _userStatus;

  UserStatus get status => _userStatus!;

  String getDate() {
    return DateFormat('yyyyMMdd').format(DateTime.now()).toString();
  }


  void getStatus(int user_id) async {
    String date = getDate();

    Dio.Response response = await dio()
        .get('/status', queryParameters: {'date': date, 'user_id': user_id});
    _userStatus = UserStatus.fromJson(response.data);

    notifyListeners();
  }
}

(models/user.dart)

class UserStatus {
  final String onlineTime;
  final int daysEarningsTotal;
  final int daysEarningsQty;
  final String vehicleModel;
  final int actualCost;

  UserStatus(
      {required this.onlineTime,
      required this.daysEarningsTotal,
      required this.daysEarningsQty,
      required this.actualCost,
      required this.vehicleModel});

  UserStatus.fromJson(Map<String, dynamic> json)
      : onlineTime = json['data']['summary']['onlineTime'],
        daysEarningsTotal = json['data']['summary']['daysEarningsTotal'],
        actualCost = json['data']['summary']['actualCost'],
        daysEarningsQty = json['data']['summary']['daysEarningsQty'],
        vehicleModel = json['data']['user']['vehicleModel'];
}

screen

class LoggedInUserStatus extends StatelessWidget {
  LoggedInUserStatus({required this.user_id});

  int user_id;

  @override
  Widget build(BuildContext context) {
    context.read<Status>().getStatus(user_id);
    return Container(
      child: Consumer<Status>(
        builder: (context, status, child) => Column(
          children: <Widget>[
            Container(
                alignment: Alignment.center,
                padding: EdgeInsets.only(top: 20),
                child: Text(
                  DateFormat('yyyy年M月d日').format(DateTime.now()),
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                )),
            Container(
              height: 250,
              color: Colors.grey,
            ),
            Container(
                margin: EdgeInsets.only(right: 15, left: 15),
                child: Column(
                  children: [
                    Container(
                        alignment: Alignment.topLeft,
                        margin: EdgeInsets.only(top: 10),
                        child: Text(
                          'ステータス',
                          style: TextStyle(
                            fontSize: 25,
                          ),
                        )),
                    Table(
                        border: TableBorder(
                          bottom:
                              BorderSide(width: 0.5, color: Color(0xFF000000)),
                        ),
                        children: [
                          TableRow(children: [
                            Text(
                              '時間',
                              style: TextStyle(color: Colors.grey),
                            ),
                            Text('数', style: TextStyle(color: Colors.grey))
                          ]),
                          TableRow(children: [
                            TableCell(
                              child: SizedBox(
                                height: 50,
                                child: Text(
                                  status.status.onlineTime,
                                  style: TextStyle(
                                    fontSize: 20,
                                  ),
                                ),
                              ),
                            ),
                            TableCell(
                              child: SizedBox(
                                height: 50,
                                child: Text(
                                  status.status.daysEarningsQty.toString(),
                                  style: TextStyle(
                                    fontSize: 20,
                                  ),
                                ),
                              ),
                            ),
                          ]),
                        ]),
                    Container(
                        alignment: Alignment.topLeft,
                        margin: EdgeInsets.only(top: 10),
                        child: Text(
                          '明細',
                          style: TextStyle(
                            fontSize: 30,
                          ),
                        )),
                    Table(children: [
                      TableRow(children: [
                        Text(
                          '売上',
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 20,
                          ),
                        ),
                        Text(status.status.daysEarningsTotal.toString(),
                            textAlign: TextAlign.right,
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 20,
                            ))
                      ]),
                      TableRow(children: [
                        TableCell(
                          child: SizedBox(
                            height: 50,
                            child: Text(
                              '支出',
                              style: TextStyle(
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                        TableCell(
                          child: SizedBox(
                            height: 50,
                            child: Text(
                              status.status.actualCost.toString(),
                              textAlign: TextAlign.right,
                              style: TextStyle(
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                      ]),
                      TableRow(children: [
                        TableCell(
                          child: SizedBox(
                            height: 50,
                            child: Text(
                              '利益',
                              style: TextStyle(
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                        TableCell(
                          child: SizedBox(
                            height: 50,
                            child: Text(
                              (status.status.daysEarningsTotal -
                                      status.status.actualCost)
                                  .toString(),
                              textAlign: TextAlign.right,
                              style: TextStyle(
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ),
                      ]),
                    ]),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text( 'ボタン'),
                      style: ElevatedButton.styleFrom(
                        primary: Colors.grey,
                        minimumSize: Size(double.infinity, 55),
                      ),
                    ),
                  ],
                ))
          ],
        ),
      ),
    );
  }
}
tmasu
  • 17
  • 5
  • 1
    That's a lot of code. Your error message contains a file name and a line. Since we don't have your line numbers, can you tell us where exactly it is? – nvoigt Mar 10 '22 at 08:25
  • Does this answer your question? https://stackoverflow.com/questions/64278595/null-check-operator-used-on-a-null-value – Yura Mar 10 '22 at 08:52

0 Answers0