Runtime Error: type 'Null' is not a subtype of type 'List<dynamic>'

Viewed 233

I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, yet I cannot figure out my most recent errors. I am getting Run time errors after installing get_storage.

My Project Modal

class Todo {
String? text;
bool done;

Todo({this.text, this.done = false});

factory Todo.fromJson(Map<String, dynamic> json) => Todo(
text: json['text'],
done: json['done'],
);

Map<String, dynamic> toJson() =>{
'text' : text,
'done' : done
};

}

My controller

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:getxtodoyapp/models/todo.dart';

class TodoController extends GetxController {
var todos = <Todo>[].obs;

@override
void onInit() {
List storedTodos = GetStorage().read('todos');

if(storedTodos != null){
todos = storedTodos.map((e) => Todo.fromJson(e)).toList().obs;
}

ever(todos, (_) {
  GetStorage().write('todos', todos.toList());
});
// TODO: implement onInit
super.onInit();
}
}

My Todo Screen

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getxtodoyapp/controllers/todoController.dart';
import 'package:getxtodoyapp/models/todo.dart';

class TodoScreen extends StatelessWidget {

final TodoController todoController = Get.find();
int? index;
TodoScreen({this.index});



@override
Widget build(BuildContext context) {
String? text ='';
if(this.index != null){

  text = todoController.todos[index!].text;

 }
TextEditingController textEditingController = TextEditingController(text: text);
return Scaffold(
  body: Container(
    padding: const EdgeInsets.all(20.0),
    child: Column(
      children: [
        Expanded(
          child: TextField(
            controller: textEditingController,
            autofocus: true,
            decoration: const InputDecoration(
                hintText: 'What do you want to accomplish',
                border: InputBorder.none,
                focusedBorder: InputBorder.none),
            style: TextStyle(fontSize: 25.0),
            keyboardType: TextInputType.multiline,
            maxLines: 999,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            ElevatedButton(
              onPressed: () {Get.back();},
              child: const Text("Cancle"),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.red),
              ),
            ),
            ElevatedButton(
              onPressed: () {
               if(this.index == null ){
                 todoController.todos.add(Todo(text: textEditingController.text), );
               }else{
                 var editing = todoController.todos[index!];
                 editing.text = textEditingController.text;
                 todoController.todos[index!] = editing;
               }
                 Get.back();

              },
              child: Text((this.index == null) ? 'Add' : 'Edit'),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.green),
              ),
            )
          ],
        ),
      ],
    ),
  ),
);
}
}

The error

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
√  Built build\app\outputs\flutter-apk\app-debug.apk.
Debug service listening on ws://127.0.0.1:57814/4gxMuwVhHhk=/ws
Syncing files to device Android SDK built for x86...
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] Instance "TodoController" has been created

======== Exception caught by widgets library 
=======================================================
The following _TypeError was thrown building HomeScreen(dirty):
type 'Null' is not a subtype of type 'List<dynamic>'

The relevant error-causing widget was: 
HomeScreen HomeScreen:file:///C:/src/projects/getxtodoyapp/lib/main.dart:8:31
When the exception was thrown, this was the stack: 
#0      TodoController.onInit (package:getxtodoyapp/controllers/todoController.dart:10:9)
#1      GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
#2      InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
#3      GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
#4      GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
#5      GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
#6      GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
#7      Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
#8      HomeScreen.build (package:getxtodoyapp/screens/homeScreen.dart:11:47)
#9      StatelessElement.build (package:flutter/src/widgets/framework.dart:4662:28)
#10     ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:4588:15)
#11     Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#12     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4566:5)
#13     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4561:5)
...     Normal element mounting (169 frames)
#182    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3631:14)
#183    MultiChildRenderObjectElement.inflateWidget 
(package:flutter/src/widgets/framework.dart:6261:36)
#184    MultiChildRenderObjectElement.mount 
(package:flutter/src/widgets/framework.dart:6272:32)
...     Normal element mounting (411 frames)
#595    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3631:14)
#596    Element.updateChild (package:flutter/src/widgets/framework.dart:3383:18)
#597    RenderObjectToWidgetElement._rebuild 
(package:flutter/src/widgets/binding.dart:1198:16)
#598    RenderObjectToWidgetElement.mount 
(package:flutter/src/widgets/binding.dart:1167:5)
#599    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> 
(package:flutter/src/widgets/binding.dart:1112:18)
#600    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2531:19)
#601    RenderObjectToWidgetAdapter.attachToRenderTree 
(package:flutter/src/widgets/binding.dart:1111:13)
#602    WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:944:7)
#603    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> 
(package:flutter/src/widgets/binding.dart:924:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and 
dart:async-patch)


================================================================================

D/skia    ( 5195): Shader compilation error
D/skia    ( 5195): ------------------------
D/skia    ( 5195): Errors:
D/skia    ( 5195): link failed but did not provide an info log
D/skia    ( 5195): Shader compilation error
D/skia    ( 5195): ------------------------
D/skia    ( 5195): Errors:
D/skia    ( 5195): link failed but did not provide an info log
D/skia    ( 5195): Shader compilation error
D/skia    ( 5195): ------------------------
D/skia    ( 5195): Errors:
D/skia    ( 5195): link failed but did not provide an info log
D/skia    ( 5195): Shader compilation error
D/skia    ( 5195): ------------------------
D/skia    ( 5195): Errors:
D/skia    ( 5195): link failed but did not provide an info log
D/EGL_emulation( 5195): eglMakeCurrent: 0xde81a120: ver 3 1 (tinfo 0xde80fa60)
1 Answers

You did not initialize GetStorage. You should do that in main function like this :

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

and turn the main function into async.

Related