-1

I'm new to programming and dont know anything. But right now, im trying to use Provider library at flutter and following some guy at youtube. But i got stuck at this situation. At first, flutter tell me to add late code, but it keep making my app error (LateInitializationError: Frield '_data@*****' has not been initialized.) So im trying to figure out this problem and i think it's about null / unnull something? (please explain this too :3) Anyway here's my code:

example_provider.dart

//Before 
//What's the difference between foundation and cupertino?
import 'package:flutter/foundation.dart';
// What is ChangeNotifier?
class ExampleProvider extends ChangeNotifier{
// Why do we need "late"? 
  late String _data;
// What is void ? 
 void setDataString(String data) {
    this._data = data;
// What is notifyListeners(); ?
notifyListeners();
  }
// Why do we need return this._data ?
  String getDataString () {
    return this._data;
  }
}

As you can see, this is my before code. i add late at String_data; because flutter told me so. But @Christoper Moore said in this forum LateInitializationError: Field 'data' has not been initialized, got error

that we must remove the late and add Question Mark(?) at our variable. Then i followed the advice/answer and change my code. Here's my after code :

example_provider.dart

//After  
//What's the difference between foundation and cu
import 'package:flutter/foundation.dart';
// What is ChangeNotifier?
class ExampleProvider extends ChangeNotifier{
// Why do we need "late"? 
   String? _data;
// What is void ? 
 void setDataString(String data) {
    this._data = data;
// What is notifyListeners(); ?
notifyListeners();
  }
// Why do we need return this._data ?
  String? getDataString () {
    return this._data;
  }
}

And then this is my homepage (which where the error occured) code : home.dart

import 'package:chapter_5/application/example_provider.dart';
import 'package:chapter_5/presentation/second_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Consumer<ExampleProvider>(
      builder: (context, exampleProvider, _) => Scaffold(
        appBar: AppBar(
          title: Text("Latihan 5"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(exampleProvider.getDataString()),
              ElevatedButton(
                child: Text("Go To Dashboard"),
                onPressed: () {
                  exampleProvider.setDataString("0");
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          SecondPage(judul: "Ayam", tulisan: "Kodok"),
                    ),
                  );
                },
                style:
                    ButtonStyle(overlayColor: MaterialStateProperty.resolveWith(
                  (states) {
                    return states.contains(MaterialState.pressed)
                        ? Colors.amber
                        : null;
                  },
                )),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Please answer my question inside my codes too so i can understand more about flutter. Thank you for answering/trying

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
Jimmy Y
  • 1
  • 1

3 Answers3

0

Try using the code in _HomePageState Widget build:

  Widget build(BuildContext context) {
    return Consumer<ExampleProvider>(
      builder: (context, exampleProvider, _) => Scaffold(
        appBar: AppBar(
          title: Text("Latihan 5"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(exampleProvider.getDataString()!),
                /* This is the line where the error occurs.
                   It happens because getDataString is nullable
                   You must add a bang operator to make it non-nullable*/
              ElevatedButton(
                child: Text("Go To Dashboard"),
                onPressed: () {
                  exampleProvider.setDataString("0");
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          SecondPage(judul: "Ayam", tulisan: "Kodok"),
                    ),
                  );
                },
                style:
                    ButtonStyle(overlayColor: MaterialStateProperty.resolveWith(
                  (states) {
                    return states.contains(MaterialState.pressed)
                        ? Colors.amber
                        : null;
                  },
                )),
              ),
            ],
          ),
        ),
      ),
    );
  }

Refer to the bang operator for more.

  • Using my after code at example_provider.dart, And following your instruction, the reuslt is still an error 'Null check operator used on a nul value' Any solution? – Jimmy Y Jul 06 '21 at 07:21
0

String? value means that value is a variable that can be null or a String

e.g.:

// This is ok
value = "Hello World";

// This is also ok;
value = null; 

If you don't assign anything to value, it is null by default.

This error:

The argument type 'String?' can't be assigned to the paramter type 'String'

it means that you are trying to assign a String? (String or null) to a String (cannot be null).

Why do we need "late"?

Because if you say String data, data is null, and String cannot be null. If you put late it is ignoring this constraints, and it will assume that somewhere else in the code (later) you will give it a value.

lenz
  • 2,193
  • 17
  • 31
  • So according to your answer, i must remove this question mark at "String?" code right? And add late before String _data; ? It still error saying : LateInitializationError: Field '_data@****' has not been initialized. – Jimmy Y Jul 06 '21 at 07:35
  • No I didn't say remove the `?`. I'm saying ***IF*** you use `late`, you need to be sure to assign something to it before using it. Otherwise it is `null` and that's an error. Try assigning it a value in the very beginning of the `build()` method, for example – lenz Jul 06 '21 at 07:38
  • I don't think I can explain better than this. You're going to have a very difficult time if you don't try to understand the basics. ****read the documentation*** https://dart.dev/null-safety/understanding-null-safety – lenz Jul 06 '21 at 07:47
  • Thank you for your time tho. Appreciate it~ – Jimmy Y Jul 06 '21 at 07:53
0

Anyway i figured it out guys. If you following my question, there's a before code on example_provider.dart Using this code, and i'll have a new error saying Lateinilization.... and then, i deleted the late String _data; code into String _data = ""; since the null safety needed a value.

//Before 

import 'package:flutter/foundation.dart';
class ExampleProvider extends ChangeNotifier{
  String _data = "";
 void setDataString(String data) {
    this._data = data;    notifyListeners();
  }
  String getDataString () {
    return this._data;
  }
}

Therefore my code is running without an error. Thank you me.

Jimmy Y
  • 1
  • 1