When assembleDebug Out of Memory error is thrown - flutter

So I'm new to flutter and dart.I've made multiple android apps and I am pretty familiar with coding but I just can't get to know flutter. I use Android Studio as Ide and when I try to compile my code , on the assembleDebug part, This error is thrown:
c:\b\s\w\ir\k\src\third_party\dart\runtime\vm\zone.cc: 54: error: Out
of memory.
version=2.4.0 (Wed Jun 19 11:53:45 2019 +0200) on "windows_x64"
thread=1336, isolate=main(0000029506C2CDE0)
pc 0x00007ff7b33d2b1b fp 0x000000d10cbfb0a0 Unknown symbol
-- End of DumpStackTrace
For now, I haven't done anything to fix the problem because I don't know why
main.dart
import 'package:flutter/material.dart';
import 'constants.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(UnitConverterApp());
}
//on create
class UnitConverterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Distivity Todolist',
theme: Constants.getTheme(),
home: CategoryRoute(),
);
}
}
class CategoryRoute extends StatefulWidget {
const CategoryRoute();
#override
_CategoryRouteState createState() => _CategoryRouteState();
}
class _CategoryRouteState extends State<CategoryRoute> {
/// Function to call when a [Category] is tapped.
void _onCategoryTap() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Center(
child: InkWell(
onTap: () => _onCategoryTap(),
child: SvgPicture.asset(
Constants.add,
semanticsLabel: 'ad'
),
)
);
}
}
constants.dart
import 'package:flutter/material.dart';
class Constants{
static ThemeData getTheme(){
return ThemeData(
primaryColor: colorSwatch,
);
}
static const primaryColor = 0xff4FB484;
static ColorSwatch colorSwatch = ColorSwatch(primaryColor, const<String,Color>{
"primary_color": Color(primaryColor),
"primary_dark":Color(0xff306D50),
"black_16": Color(0xff161616),
"black_20":Color(0xff202020),
"the_blackest":Color(0xff000000),
"color_white":Color(0xffF7F7F7),
"the_whitest":Color(0xffffffff)
});
static const String add = 'assets/add.svg';
}
pubspec.yaml
name: distivity_todolist
description: A new Flutter application.
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_svg: 0.13.1
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/add.svg

Related

Flutter: Coding so that the logic waits until class members are populated before rendering app on screen

A flutter newbie, I'm trying to get my app to take values from a local json file and render them on-screen.
The logic isn't waiting for the class constructor to populate the relevant string variable before rendering the app on screen.
Here's the code that illustrates my problem.
First, my main.dart file:
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'sampleDataClass.dart';
import 'package:provider/provider.dart';
String assetFilePath = 'assets/basicData.json';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (details) {
FlutterError.presentError(details);
if (kReleaseMode) exit(1);
};
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: const MaterialApp(
title: "Sample screen",
home: MyHomePage(),
)
);
}
}
class MyAppState extends ChangeNotifier {
SampleDataClass current = SampleDataClass(assetFilePath);
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
#override
Widget build(BuildContext context) {
var myAppState = context.watch<MyAppState>();
var myAppBasicData = myAppState.current;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo,
foregroundColor: Colors.amberAccent,
title: const Text("This is the App Bar"),
elevation: 10,
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Expanded(
child: Container(
color: Colors.blueGrey,
padding: const EdgeInsets.all(10),
child: (
Text(myAppBasicData.language,
style: const TextStyle(
color: Colors.white,
))))),
]),
]
),
);
}
}
Here is my SampleDataClass.dart file:
import 'dart:core';
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
class SampleDataClass {
String classFilePath = "";
String language = "not populated";
String batteryName = "not populated";
SampleDataClass(filePath) {
rootBundle.loadString(filePath).then((jsonDataString) {
Map classDataMap = jsonDecode(jsonDataString);
language = classDataMap['language'];
print(language);
batteryName = classDataMap['batteryName'];
print(batteryName);
});
}
Map<String, dynamic> toJson() => {
'language': language,
'batteryName': batteryName,
};
}
And here's my pubspec.yaml file:
name: samples
description: A new Flutter project.
environment:
sdk: '>=2.18.6 <3.0.0'
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
provider: ^4.1.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/basicData.json
Finally, my basicData.json file looks like this:
{
"language": "English",
"batteryName": "Exercise 32"
}
The print statements in the sampleDataClass class work fine but as you can see if you run the code (from the command line using "flutter run --no-sound-null-safety"), the app renders the initial values of the variables before the class constructor assigns the json values to them.
What I expected was the class constructor to complete writing the relevant json values to the class members before handing back the class instance to the build widget in main.dart to render the app on-screen.
I realise that this is a very elementary question, but it is a key pending learning task for me!
Thank you all very much in advance!
it looks like rootBundle is an async function, you have to wait till it finishes then you notify the UI to render with new data,
How to handle this :
you should have 3 states loading state , error state , loaded state ,
create an init(path) function in SampleDataClass class that returns SampleDataClass instance.
Also, in the init() function at the beginning you have to change the state to loading state then when you get the data you set the state to loaded state, then notify listeners this will help the screen to know which state the page is in.
in the screen , call didChangeDependencies() and inside it, call your Provider => init function ( current = contecxt.read<YPUR_PROVIDER>().init(path); )
therefore the current object is being initialized, the page is showing a loader, and once the initialization is done, the provider will notify the page and it will change the loading view to the loaded view (your current view).
Another Tip::
your app will close whenever there is an error, it is not a good practice, since flutter will through non-fatal exception
FlutterError.onError = (details) {
FlutterError.presentError(details);
if (kReleaseMode) exit(1);
There is a choice of two excellent solutions to my problem with very little effort and no need for any change management (yet).
Indeed, so similar is the problem described that I probably should have found it before I posted this query here. As a newbie in this discipline, I clearly didn't conduct my search with the appropriate key words; for that I apologise!
Thanks very much to everyone for your patience.
The two solution options (which even I was able to follow) can be found here:
Calling an async method from a constructor in Dart

pub.dev - my package not showing platforms correctly (web missing)

I developed a flutter package multi_image_picker_view:
https://pub.dev/packages/multi_image_picker_view
This package depends on file_picker and flutter_reorderable_grid_view, they both support the Web. But in my package, web option is not visible in pub.dev. Even this package works fine on the web.
👉Help me to figure out why WEB is not showing on pub.dev.
📜My pubspec.yaml
name: multi_image_picker_view
description: A complete widget that can easily pick multiple images from a device and display them in UI. Also picked image can be re-ordered and removed easily.
version: 0.0.6
homepage: https://github.com/shubham-gupta-16/multi_image_picker_view
repository: https://github.com/shubham-gupta-16/multi_image_picker_view
issue_tracker: https://github.com/shubham-gupta-16/multi_image_picker_view/issues
environment:
sdk: ">=2.17.1 <3.0.0"
flutter: ">=1.17.0"
dependencies:
flutter:
sdk: flutter
flutter_reorderable_grid_view: ^3.1.3
file_picker: ^5.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
assets:
- packages/multi_image_picker_view/assets/close-48.png
👨‍💻Commands I used to publish
flutter pub publish
🗃️My Matchine Info
Flutter Version: 3.0.1
Channel: Stable
Dart Version: 2.17.1
IDE: Android Studio Chipmunk | 2021.2.1 Patch 1
🚀You can find the complete code Github:
https://github.com/shubham-gupta-16/multi_image_picker_view
Thank you in advance.
Conditional import required
The reason why this package is not showing Web on pub.dev is that it uses dart.io without conditional import.
To fix this, I separated the file where it is used. One for web and one for non-web platforms. Then import them by using conditions based on the running platform.
web_preview.dart
import 'package:flutter/material.dart';
import '../image_file.dart';
class ImagePreview extends StatelessWidget {
final ImageFile file;
const ImagePreview({Key? key, required this.file}) : super(key: key);
#override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.memory(
file.bytes!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return const Center(child: Text('No Preview'));
},
),
);
}
}
non_web_preview.dart
import 'dart:io'; // here I imported dart:io
import 'package:flutter/material.dart';
import '../image_file.dart';
class ImagePreview extends StatelessWidget {
final ImageFile file;
const ImagePreview({Key? key, required this.file}) : super(key: key);
#override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.file(
File(file.path!), // Now I can use File class
fit: BoxFit.cover,
),
);
}
}
my_package_file.dart
...
import 'non_web_preview.dart' if (dart.library.html) 'web_preview.dart'; // conditional import
class MyPackageFile extends StatelessWidget {
...
#override
Widget build(BuildContext context) {
return ImagePreview(file: imageFile); // Using ImagePreview class
}
}

FlutterLab: Error: Null safety features are disabled for this library

I am using FlutterLab but encounter the below error:
⭐ Build started at Tuesday, August 31st 2021, 10:55:04AM +10:00 ⭐
🏁 Build finished at Tuesday, August 31st 2021, 10:55:15AM +10:00 🏁
❌ Build failed. Check the logs below
Compile failed
/lib/main.dart:24:21: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
const MyDiary({Key? key}) : super(key: key);
^
No branch
with the below code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
// Application name
title: 'Flutter Hello World',
// Application theme data, you can set the colors for the application as
// you want
theme: ThemeData(
primarySwatch: Colors.blue,
),
// A widget which will be started on application startup
home: MyDiary(),
);
}
}
class MyDiary extends StatelessWidget {
const MyDiary({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container();
}
}
How can I fix the code?
Solution: sdk: ">=2.12.0 <3.0.0" in pubspecs.yml

Flutter Hive package initialisation error

I tried use Hive package in my application. But when I initialised in my app get error message:
The following HiveError was thrown building MyApp(dirty): Box not
found. Did you forget to call Hive.openBox()?
Her is my code:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart' as path_provider;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocDir = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocDir.path);
runApp(MyApp());
final box = await Hive.openBox('storage');
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final box = Hive.box('storage');
return MaterialApp(
title: 'Test App',
debugShowCheckedModeBanner: false,
home: CheckAuth(),
);
}
}
class CheckAuth extends StatefulWidget {
#override
_CheckAuthState createState() => _CheckAuthState();
}
class _CheckAuthState extends State<CheckAuth> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Text('Hive initialised!'),
);
}
}
Emulator
API: 28
Android: 9
Packages
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
hive: ^1.4.4+1
hive_flutter: ^0.3.1
http: ^0.12.2
cupertino_icons: ^1.0.0
path_provider: ^1.6.24
dev_dependencies:
flutter_test:
sdk: flutter
hive_generator: ^0.8.2
build_runner: ^1.10.11
flutter:
uses-material-design: true
Where I have any error in my code?
Why don't you use await Hive.initFlutter() instead of Hive.init()? The former is supposed to take care of proper app folder path on specific platform and put it's files there.
It is part of package:hive_flutter/hive_flutter.dart which deals with Flutter specific stuff

How to get BlockProvider recognized in my flutter project?

So, I'm trying out the BLOCK pattern recently and after having imported the block_pattern package in my pubsec yaml file like this
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
bloc_pattern: ^2.2.2+3
rxdart:
Now, I have establish a class called CartListBloc as an extend of BlockBase
class CartListBloc extends BlocBase {
CartListBloc();
//etc...
When I try to put a BlockProvider in the main class it isn't recognized by the IDE despite having the correct imports.
import 'package:bloc_pattern/bloc_pattern.dart';
import 'bloc/cartListBloc.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlockProvider( // here it doesn't recognize BlockProvider
blocs: [
],
child:
);
}
}
You have to get rid of the k in BlocProvider
import 'package:bloc_pattern/bloc_pattern.dart';
import 'bloc/cartListBloc.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider( // remove the K
blocs: [
],
child:
);
}
}