I am writing my first Flutter app. The app allows the user to take multiple images (from 1 to 50+), and displays each image on the screen all at once using the ListView.
The issue I am having is, the app crashes after roughly 10/12 pictures on the Samsung SM A520F, am guessing this is due to the fact that this is not a very powerful device.
Is there a way I can display the thumbnail of the image instead of loading the full size image?
Error message:
I don't actually get any error messages, the app just seems to restart!
Here is my code
import 'package:flutter/material.dart';
import 'package:myapp/utilities/app_constants.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:gallery_saver/gallery_saver.dart';
class FormCameraField extends StatefulWidget {
final InputDecoration decorations;
final Map field;
// functions
final Function onSaved;
final Function onFieldSubmitted;
FormCameraField({
this.decorations,
#required this.field,
#required this.onSaved,
#required this.onFieldSubmitted,
});
#override
_FormCameraFieldState createState() => _FormCameraFieldState();
}
class _FormCameraFieldState extends State<FormCameraField> {
List<File> images = [];
Future<void> _takePhoto(ImageSource source) async {
ImagePicker.pickImage(source: source, imageQuality: 90).then(
(File recordedImage) async {
if (recordedImage != null && recordedImage.path != null) {
try {
// store image to device gallery
if (widget.field["StoreCaptureToDevice"] == true) {
GallerySaver.saveImage(recordedImage.path,
albumName: kAppName.replaceAll(" ", "_"));
}
setState(() {
images.add(recordedImage);
});
} catch (e) {
print("ERROR SAVING THE FILE TO GALLERY");
print(e);
}
}
},
);
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MaterialButton(
child: Text("Take Photo"),
onPressed: () async {
await _takePhoto(ImageSource.camera);
},
),
),
Expanded(
child: MaterialButton(
child: Text("Select Photo"),
onPressed: () async {
await _takePhoto(ImageSource.gallery);
},
),
),
],
),
ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: images.length,
itemBuilder: (BuildContext context, index) {
return Container(
child: Image.file(
images[index],
),
);
},
)
],
);
}
}
I faced the same problem.
This is because some images cause the crash of Flutter engine.
The final issue is here https://github.com/flutter/flutter/issues/73767
The example image that always causes crash on ios is here
https://github.com/flutter/flutter/issues/73932
So, waiting for the Flutter team fixes the bug.
Having a similiar problem. Replacing my images with smaller (~50kb) ones seems to be working fine so i think you are right, loading all those images on less powerfull devices seems to be the problem. There is an image package on pub.dev that should do the trick. I am using Firebase so i will lean more towards their new resize image extension. Goodluck and let us know if it works
I have the same problem. It's actually a bug in flutter. They are currently working to fix the bug in the next stable releases.
I created thumbnails, this worked for me.
Related
I am new to flutter. I am getting image from backend and displaying those images on the screen using Hero and FadeInImage.
I ave added the hyperlinks in the images and generating the list of images after hitting the API.
child: Hero(
tag: tag,
child: FadeInImage(
width: 130.0,
height: 186.0,
placeholder: AssetImage('assets/images/splash1.png'),
fit: BoxFit.cover,
// onTap: _launchUrl(),
image: NetworkImage(
(merchant.logo)),
// fit: BoxFit.cover,
),
),
),
),
when I run my app, the images are not loaded; the screen is empty. But when I hot reload it shows.
...List.generate(
merchantsList.length,
(index) {
print(merchantsList.length);
print(index);
return MerchantCard(merchant: merchantsList[index]);
You can use placeholder image and also you can add Future Builder concept and Please once check the Future Concept.
#override
Widget build(BuildContext context) {
return new FutureBuilder(
future: _loadImage(),
builder: (BuildContext context, AsyncSnapshot<Image> image) {
if (image.hasData) {
return image.data; // image is ready
} else {
return new Container(); // placeholder
}
},
);
}
The problem was actually widget was built before values are populated in the list. I used setState on my listPopulated function and it worked perfectly ok.
I'm developing my first app with flutter. At some point I was wondering :Am I developping the UX part correctly ? Meaning am I using the proper widget, is there any better way to do that etc.. I find out about Flutter Performance on Intellj Idea and I saw that most of the pages I developed are red...
FYI : The code I created for a simple page
Flutter inspector result => radio-btn-aligned
import 'package:flutter/material.dart';
import 'package:testapp/my_theme.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: MyAppTheme(ctx: context).defaultTheme,
home: new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: AddDailyTaskPage()),
);
}
}
enum Options { goal, category }
class AddDailyTaskPage extends StatefulWidget {
#override
_AddDailyTaskPageState createState() => new _AddDailyTaskPageState();
}
class _AddDailyTaskPageState extends State<AddDailyTaskPage> {
Options _options = Options.goal;
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
child: Text("Task Description"),
),
Container(child: Row(
children: [
Expanded(
child: Row(
children: [
Radio<Options>(
value: Options.goal,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
Text(
'Goal',
style: new TextStyle(fontSize: 16.0),
)
]
)
),
Expanded(
child: Row(
children: [
Container(
child: Radio(
value: Options.category,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
),
Container(
child: Text(
'Category',
style: new TextStyle(
fontSize: 16.0,
),
),
)
],
)
)
],
),)
// Container(
// child: TextField(
// maxLines: 10,
// decoration: InputDecoration(
// // suffixIcon:
// focusedBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.grey, width: 5.0),
// ),
// enabledBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.black, width: 5.0),
// ),
// hintText: 'Description task',
// ),
// ),
// )
],
),
);
}
}
To see the difference, I checked the sample code provided while creating a flutter Project
FYI :
flutter performance result : auto-increment
As we can see on the previous pic, it doesn't seems optimised.. :/
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(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Few questions :
1/ Does anyone has / knows a good flutter repo with ton of examples based on performance ?
2/ What is your standard in term of perf ? I mean on my virtual device, the UX seems fluid but if the Flutter Perf is "red", then I'm guessing I'm doing something wrong and there is a better way to do ?
3/ Do you guys knows a website / forum / someone who's willing to do a core review once a week to help me implementing good pattern in my flutter application ?
4/ What is wrong with my current design ? What is wrong with the default design ? Why the performance are doesn't seems good ? I started to read the official documentation for the perf, but how could I know if the UX itself have good perf or not ? Actually by testing some stuff, I find out that putting everything in Container / Row or Column widget, improved a lot the performance but even with this widgets, it's not enough :/
Any advice ?
Thanks for your help
You use a StatefulWidget for the whole page. That means that when you call setState() the whole page gets rebuild.
One example is:
Radio<Options>(
value: Options.goal,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
There's no need to rebuild your whole page when you set an option. If you extract that code out into it's own StatefulWidget, only this portion gets rebuild.
You can click on "Track Widget rebuilds" to see what Widgets do rebuild in your app and then think about whether those Widget actually should rebuild.
Once you do smaller Widgets you get the problem that events in one Widget are supposed to influence other Widgets. That's when state management solutions come into play. The weather example of the Bloc package shows a good structure of an app that you can copy.
I have a Flutter website built on channel beta that is used for uploading large images.
When testing on Chrome, scrolling down when there are large number of image rows it is extremely laggy.
Below is a sample reproduction of the code
import 'package:flutter/material.dart';
import 'package:flutter_dropzone/flutter_dropzone.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
DropzoneViewController controller1;
String message1 = 'Drop something here';
bool highlighted1 = false;
List assets = [];
#override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Dropzone example'),
),
body: ListView(
children: [
if (assets.length > 0)
_showAssets(assets)
else
buildZone1(context),
Padding(
padding: const EdgeInsets.all(30),
child: Container(
width: 100,
child: MaterialButton(
color: Colors.greenAccent,
child: Text('Browse files'),
onPressed: () =>
controller1.pickFiles(multiple: true).then((files) {
files.forEach((file) {
controller1.createFileUrl(file).then((url) {
setState(() {
print('in set state');
assets.add(url);
});
});
});
}),
),
),
),
Container(height: 400, color: Colors.lightGreen),
Container(height: 400, color: Colors.redAccent),
],
),
),
);
Widget _showAssets(List assets) {
//print(assets);
return Wrap(
children: assets.map((asset) {
return Container(
height: 150,
child: Image.network(asset),
);
}).toList(),
);
}
Widget buildZone1(BuildContext context) => Builder(
builder: (context) => Container(
height: 200,
child: DropzoneView(
operation: DragOperation.copy,
cursor: CursorType.grab,
onCreated: (ctrl) => controller1 = ctrl,
onLoaded: () => print('Zone 1 loaded'),
onError: (ev) => print('Zone 1 error: $ev'),
onHover: () {
setState(() => highlighted1 = true);
//print('Zone 1 hovered');
},
onLeave: () {
setState(() => highlighted1 = false);
//print('Zone 1 left');
},
onDrop: (ev) {
print('Zone 1 drop: ${ev.name}');
setState(() {
print('in set state');
message1 = '${ev.name} dropped';
highlighted1 = false;
});
},
),
),
);
}
pubspec.yaml
name: file_upload
description: A new Flutter project.
publish_to: 'none'
https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_dropzone: ^1.0.9
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.1
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
To reproduce
Click on Browse files and select over 50 to 100 images of over 2MB to display over 10 rows
Try to scroll down when the images are visible
You're not lazily building the pictures. Use ListView.builder instead.
The documentation states in regard to the default ListView constructor:
This constructor is appropriate for list views with a small number of children because constructing the List requires doing work for every child that could possibly be displayed in the list view instead of just those children that are actually visible.
With 50 to 100 2MB images, it would be understandable that your computer is having a hard time.
The documentation states that the ListView.builder constructor builds children on demand.
The ListView.builder constructor takes an IndexedWidgetBuilder, which builds the children on demand. This constructor is appropriate for list views with a large (or infinite) number of children because the builder is called only for those children that are actually visible.
Ex.
ListView.builder(
itemBuilder: (context, index) {
if (assets.length > 0) {
if (assets[index] == null) {
return null;
}
return Container(
height: 150,
child: Image.network(assets[index]),
);
}
else {
if(index > 0) {
return null;
}
return buildZone1(context);
}
},
)
I had the same problem, I solved it by compressing and downsizing the images to the lowest possible form while maintaining fidelity. that compressed images showed major improvements in the lag specially while scrolling
When dragging modal bottom sheets, the flutter application starts lagging if a lot of widgets live inside the sheet. This only occurs on the modal bottom sheet (showModalBottomSheet) and not on the normal one (showBottomSheet).
Below I attached a screenshot of the performance analysis, which shows, that all widgets inside the sheet are beeing constantly rebuilt while the user is dragging.
I wrote a little demo to compare the performance of the two types of sheets. Is there a way to prevent the rebuilding while dragging?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "demo",
home: Scaffold(
body: MyButtons(),
),
);
}
}
class MyButtons extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (context) => BottomSheet(),
);
},
child: Text("show modal (laggy)"),
),
RaisedButton(
onPressed: () {
showBottomSheet<void>(
context: context,
builder: (context) => BottomSheet(),
);
},
child: Text("show normal (not laggy)"),
),
],
),
);
}
}
class BottomSheet extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Wrap(
spacing: 8.0,
alignment: WrapAlignment.center,
children: List<Widget>.generate(
100,
(int index) {
return InputChip(
label: Text("test"),
);
},
),
);
}
}
I have created this PR to fix this performance issue. The problem was that the AnimatedContainer from the ModalBottomSheet was not using the child property and therefore it was forcing to call builder method many times while animation is running instead of using the already built child widget.
just update flutter to latest version. kudos to Enol Casielles Martinez
I saw linear degradation of framerate UI when I launch speed_dial animation plugin. The problem appear when I add sharedpref function here:
#override
Widget build(BuildContext context) {
sharedpref_function();
return Scaffold(
to listen a saved value, even If the sharedpref is empty I have this degradation.
After 10min whithout doing nothing before, I measure 1120ms/frame when I call _renderSpeedDial
Here is the full code :
bool _dialVisible = true;
Color _speedDial = Colors.pink;
sharedpref_function() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
}
);
}
_renderSpeedDial() {
return SpeedDial(
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 22.0),
backgroundColor: _speedDial,
// child: Icon(Icons.add),
/* onOpen: () => print('OPENING DIAL'),
onClose: () => print('DIAL CLOSED'),*/
visible: _dialVisible,
curve: Curves.bounceIn,
children: [
SpeedDialChild(
child: Icon(Icons.fullscreen_exit, color: Colors.white),
backgroundColor: Color(0xffa088df),
onTap: () {
setState(() {
});
},
label: '1',
labelStyle: TextStyle(fontWeight: FontWeight.w500,color: Colors.white),
labelBackgroundColor:Color(0xffa088df),
),
],
);
}
#override
Widget build(BuildContext context) {
sharedpref_function(); // here the sharedpref I use to listen saved value
return Scaffold(
body: Stack(
children: <Widget>[
Padding
(
padding: const EdgeInsets.only(right:10.0, bottom:10.0),
child:
_renderSpeedDial(),
),
],
)
);
}
}
Your sharedpref_function() method is being called inside your build method. That's not recommended at all because it will be called on every frame the UI needs to be rebuild and your code, having an animation there, will be called at 60fps (on every frame).
Move your method inside initState or didChangeDependencies (there're even more methods that get called once or a few times like didChangeDependencies).
When you need to update values, you could do it inside an onTap gesture and that's it.
Also, test your app in --release (release mode) to truly test the speed of your app.