Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know whether late init has been initialized in dart(flutter)?

I am fetching data from url in Flutter. I have a late init Map called tables. I am fetching data inside initState() function. When I first launch the app, I am getting LateInizialization error on the red screen. I want to detect whether late init is initialized and display spinner if it is not initialized. This is my code.

class TablesTab extends StatefulWidget {
  @override
  _TablesTabState createState() => _TablesTabState();
}

class _TablesTabState extends State<TablesTab> {
  late List<dynamic> tables;
  var refreshKey = GlobalKey<RefreshIndicatorState>();
  GetUriData tablesInstance = new GetUriData(url: '/api/table/getAllTables');

  void getTables() async {
    tables = await tablesInstance.getData();
  }

  @override
  void initState() {
    super.initState();
    getTables();
  }

  Future<void> refreshList() async {
    refreshKey.currentState?.show(atTop: false);
    // await Future.delayed(Duration(seconds: 2));
    var updatedTables = await tablesInstance.getData();
    setState(() {
      tables = updatedTables;
    });

    //network call and setState so that view will render the new values
    print(tables);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
          child:  GridView.count(
            crossAxisCount: 4,
            children: List.generate(this.tables.length, (index) {
              return Center(
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, '/tableReview', arguments: {'table': this.tables[index]});
                  },
                  child: Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                          border: Border.all(color: Theme.of(context).primaryColor, width: 2.0),
                          borderRadius: BorderRadius.all(Radius.circular(70))
                      ),
                      padding: const EdgeInsets.all(14.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '${this.tables[index]['tableNum']}',
                            style: TextStyle(
                                color: Theme.of(context).primaryColor,
                                fontSize: 23
                            ),
                          ),
                        ],
                      )
                  ),
                ),
              );
            }),
          ),
          onRefresh: refreshList
      )
    );
  }
like image 272
Sardorek Aminjonov Avatar asked Mar 24 '21 07:03

Sardorek Aminjonov


People also ask

How to tell if a variable has been initialized late in Dart?

Dart offers no way to tell if a late variable has been initialized or assigned to. If you access it, it either immediately runs the initializer (if it has one) or throws an exception. Sometimes you have some state that’s lazily initialized where late might be a good fit, but you also need to be able to tell if the initialization has happened yet.

How to check if late init is initialized or not?

You can't check the initialization state of a late variable. If that's something you need to know, you either will need to add and maintain a separate flag or make the variable nullable and compare to null instead. I want to detect whether late init is initialized and display spinner if it is not initialized.

What happens if we don’t initialize lateinit variable before using it?

If we don’t initialize a lateinit variable before using it gives an error of “lateinit property has not been initialized”. You can check if the lateinit variable has been initialized or not before using it with the help of isInitialized () method.

How to declare variables that will be initialized later in C++?

Declaration of variables that will be initialize later is done using late modifier. while using late before variables make sure that, variable must be initialized later. Otherwise you can encounter a runtime error when the variable is used. 2.


1 Answers

You can't know whether late field initialized or not.

I don't think you should use late in that case. Adding late to field means that the field will be initialized when you use it for the first time. In your code the field can be not initialized, so you'd better to use tables without late, initialize it with empty list and use boolean flag to indicate loading:

  var tables = [];
  var loading = false;

  ...

  Future<void> refreshList() async {
    ...
    setState(() {
      loading = true;
    });
    var updatedTables = await tablesInstance.getData();
    setState(() {
      tables = updatedTables;
      loading = false;
    });
    ...
  }
like image 66
Mol0ko Avatar answered Oct 04 '22 17:10

Mol0ko