Val
Val

Reputation: 1822

Flutter app executes same line of code 5 times

I hve a simple Flutter app which reads a JSON file and then prints the contents to the output console. While debugging it step by step I noticed that the line with the File instatiation is executed five times (I need to press F10 five times) before advancing to the next line.

import 'package:flutter/widgets.dart';
import 'dart:io';
import 'dart:convert';
import 'package:path_provider/path_provider.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
    @override
    Widget build(context)
    {
        getApplicationDocumentsDirectory().then(
            (Directory dir)
            {
                File jsonFile = new File(dir.path + "/" + "appstorage.json"); // This line executes 5 times
                bool fileExists = jsonFile.existsSync();
                
                if(fileExists)
                {
                    String fileContentAsString = jsonFile.readAsStringSync();
                    Map<String, dynamic> fileContent = json.decode(fileContentAsString);
                    print(fileContent);
                }
            }
        );

        return Center(child: Text('Hello Flutter!', textDirection: TextDirection.ltr));
    }
}

What could cause this behavior? First I thought maybe this code is executed asynchronuously and there are some other commands executed elsewhere while my branch is still on the same spot but I don't see how there could be other code running on a separate thread.

Upvotes: 0

Views: 181

Answers (1)

Thierry
Thierry

Reputation: 8383

The build method of a Widget can (and will) be called multiple times. You should move the initialization into the initState of a StatefulWidget or, if you use Flutter Hooks, into a useEffect.

Upvotes: 2

Related Questions