I have a really simple program:
import 'dart:io';
void main(){
print('Please enter the first number.');
var firstNumber = stdin.readLineSync();
print('Please enter the second number.');
var secondNumber = stdin.readLineSync();
double result = double.parse(firstNumber!) double.parse(secondNumber!);
print('The result is $result');
}
and when I run it, I get this error:
Launching lib\main.dart on sdk gphone 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:52429/lSfmo-Ts5b8=/ws
Syncing files to device sdk gphone x86...
I/flutter ( 9916): Please enter the first number.
I/flutter ( 9916): Please enter the second number.
E/flutter ( 9916): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 9916): #0 main (package:ex1/main.dart:8:43)
E/flutter ( 9916): #1 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:130:25)
E/flutter ( 9916): #2 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 9916): #3 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 9916): #4 _runZoned (dart:async/zone.dart:1861:10)
E/flutter ( 9916): #5 runZonedGuarded (dart:async/zone.dart:1849:12)
E/flutter ( 9916): #6 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:126:5)
E/flutter ( 9916): #7 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
E/flutter ( 9916): #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter ( 9916):
Android Studio doesn't ask for input for both the stdin functions. It just throws the error. The flutter example app runs fine. I don't really know what is wrong there. Please help.
CodePudding user response:
I have the same issue and the solution is adding
WidgetsFlutterBinding.ensureInitialized() in main function before run app:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// init your dependency injection here
runApp(MyApp());}
From the docs:
Returns an instance of the WidgetsBinding, creating and initializing it if necessary. If one is created, it will be a WidgetsFlutterBinding. If one was previously initialized, then it will at least implement WidgetsBinding.
You only need to call this method if you need the binding to be initialized before calling runApp.
CodePudding user response:
i think you can't take input from your console like this, it's better you can use emulator or real device and run on that device and then you take values from user.