This simple app works fine in debug mode but not release mode:
main.dart:
import 'package:flutter/material.dart';
void main() {
ErrorWidget.builder = (FlutterErrorDetails details) {
bool inDebug = false;
assert(() { inDebug = true; return true; }());
// In debug mode, use the normal error widget which shows
// the error message:
if (inDebug)
return ErrorWidget(details.exception);
// In release builds, show a yellow-on-blue message instead:
return Container(
alignment: Alignment.center,
child: Text(
'Error! ${details.exception} ${details.stack}',
style: TextStyle(color: Colors.red),
textDirection: TextDirection.ltr,
),
);
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyWidget(),
);
}
}
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Builder(
builder: (context) {
var list = <int>[1,2,3,4];
List<int?> nullable = list.sublist(2); // also try "nullable = list"
nullable.add(null);
return Center(
child: Text("nullable $nullable list $list")
);
}
)
);
}
}
Have a look at this snippet:
List<int> list = [1,2,3,4];
List<int?> nullable = list.sublist(2);
nullable.add(null);
print("nullable $nullable list $list");
It prints "nullable [3, 4, null] list [1, 2, 3, 4]"
When you change the code to:
List<int> list = [1,2,3,4];
List<int?> nullable = list;
nullable.add(null);
print("nullable $nullable list $list");
It prints: "nullable [1, 2, 3, 4, null] list [1, 2, 3, 4, null]"
So, in the first example it works as I'd expect. But in Flutter it works like that only in the debug mode. When I create an apk in release mode it throws an exception (Null is not a subtype of 'int').
The second example might be understandable too, but it might be unexpected that we end up with a variable which should allow nulls, but when you try to add a null it throws an error.
So, my question here is why does the debug mode in Flutter work like that and can we somehow change it so that it behaves just like in the release mode.
I'm using VS Code, Flutter 3.7.0