How does the build widget get executed in flutter? - dart

It is a really beginner question but have to ask for my learning satisfaction
Code snippet from flutter / dart app :
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("MY FIRST APPLication"),
),
),
);
}
I understand what this code does but what I am not understanding what 'home' and 'appBar' ? Is home a variable defined inside MaterialApp or a widget.
What does ':' signifies? does it means we are creating a new widget - in this case Scaffold - and storing it in home or home is referencing to Scaffold ?
Can someone clarify this ?
(I tried google)
Thanks,

'home' and 'appBar' are properties of widget in flutter.
You can also take a look https://docs.flutter.io/flutter/material/Scaffold-class.html, https://docs.flutter.io/flutter/material/MaterialApp-class.html.

Related

Why Tab Indent is not Consistent in VSCode ? (Dart Language)

I want to ask about the "Format Document" feature, why when using the "document format" feature in VScode, the tabulation becomes irregular like the code that I attached below.
I have tried to set "Editor: tab size" to 2 but when I use "Format Document", my code becomes irregular.
#override
Widget build(BuildContext context) {
````return new Container(
````````child: new Column(
``````children: <Widget>[
````````new Row(
``````````children: <Widget>[
````````````//slideshow
````````````new Expanded(
````````````````child: new CarouselSlider(
``````````````height: 150.0,
I expect the code like this :
#override
``Widget build(BuildContext context) {
````return new Container(
``````child: new Column(
````````children: <Widget>[
``````````new Row(
````````````children: <Widget>[
``````````````//slideshow
``````````````new Expanded(
````````````````child: new CarouselSlider(
````````````````height: 150.0,
The formatting is done by dart_style/dartfmt, and its convention is 2-space indenting, with 4 spaces for continued lines.
For Flutter code this often isn't the best formatting, so trailing commas can be used to change the formatting a little that works better:
https://flutter.dev/docs/development/tools/formatting#using-trailing-commas
(source: flutter.dev)
After poking around for solutions to this for months, thinking it must have something to do with the line length, the word wrapping, or other things, and none of it worked, I realized that if one has "Enable SDK Formatter" checked, it will seemingly override all of that with dart_style's choices.
Kind of sad to turn it off, as I'm sure it must be doing some other things that are useful. But I just can't live with that odd formatting that obfuscates the actual structure of the code as soon as I hit Save. So, if you're doing it manually in the settings.json, I would do:
"dart.enableSdkFormatter": false,

Is there a way to display an image if the requested image is not in my assets?

the title might be a bit confusing but i'll try to explain it better with an example.
I am using the widget
Image.asset(
'assets/images/${object.name}.jpg',
),
but i want to show a default image (from assets or network) if the selected one is not available.
Is this possible?
Thanks.
You can use the errorBuilder function to return another widget if the asset loading fails.
Widget createImage(String iconName) {
return Image.asset('assets/icons/${iconName}.png',
errorBuilder: (context, object, stacktrace) =>
Image.asset('assets/icons/default.png'));
}
If you are looking for a placeholder you could use the following package here.
CachedNetworkImage(
imageUrl: "http://via.placeholder.com/350x150",
placeholder: new CircularProgressIndicator(),
errorWidget: new Icon(Icons.error),
),

How to open a Flutter dialog no matter where the user is within the app

I'm working on a Flutter project where I need the ability to show the user a dialog no matter where they happen to be within the app. Currently I'm executing the showDialog() function in the root level widget that main() kicks off.
That widget implements WidgetsBindingObserver so that I can listen for when the app moves from the background to the foreground via the didChangeAppLifecycleState() function. Anytime this happens I make a request to a service provider and depending on the results I need to show a dialog.
The users will be navigated to some other route anytime this happens, and that's where I seem to be running into trouble. Below is the stripped down function that performs the API call and subsequent showDialog() attempt. But nothing ever happens. I tried wrapping it in a 2 second timer thinking maybe it was an issue of the app just coming back into the foreground, but that didn't make a difference.
void _fetchSuperAwesomeStuff() {
final apiCaller = new SuperAwesomeStuffAPI();
apiCaller.fetchSuperAwesomeStuff().then((List<SuperAwesomeStuff> superAwesomeStuffs) {
if (superAwesomeStuffs != null && superAwesomeStuffs.length > 0) {
SuperAwesomeStuff superAwesomeStuff = superAwesomeStuffs[0];
// .... DOING STUFF WITH THIS SUPER AWESOME STUFF .... //
// NEED TO SHOW A DIALOG.
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: Text('Test Title'),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text('Close'),
),
],
),
);
}
});
}
Any help with this would be greatly appreciated, thank you!
You need to pass a BuildContext for the context variable, and that context needs to be mounted (the corresponding element) in the tree when you make the call.
Alternatively, you could send a message/stream from your superawesome logic to any part of the app that has a context and listens to the stream. From here you could call the dialog.

Flutter Android PreferenceScreen settings page

Android has PreferenceScreen which provides you the consistent Settings interface and handles a lot of SharedPreferences functionality on its own.
Is there anything similar in Flutter or do I have to create it by my own using custom ListView?
So, there doesn't exist any widget like that, you will have to create it on your own and handle their action in onChanged or onTap events. For example:
CheckBoxPreference
CheckboxListTile(
value: true,
title: Text("This is a CheckBoxPreference"),
onChanged: (value) {},
),
SwitchPreference
SwitchListTile(
value: false,
title: Text("This is a SwitchPreference"),
onChanged: (value) {},
),
ListPreference
ListTile(
title: Text("This is a ListPreference"),
subtitle: Text("Subtitle goes here"),
onTap: (){},
)
In Flutter the easiest way to make a PreferenceScreen page is with a ListView and ListTiles.
ListView(children: <Widget>[
ListTile(
title: Text('Enable Feature'),
trailing: Checkbox(
value: PrefService.getBool('feature_enabled'),
onChanged: (val) {
setState(() {
PrefService.setBool('feature_enabled', val);
});
},
),
onTap: () {
setState(() {
PrefService.setBool(
'feature_enabled', !PrefService.getBool('feature_enabled'));
});
},
)
]),
But you still need to listen for changes and save them.
To make that easier you can use the package preferences. It removes the boilerplate code and manages saving the changes. The example above would look like this with preferences:
PreferencePage([
CheckboxPreference(
'Enable Feature',
'feature_enabled',
)
]),
You can find it under https://pub.dartlang.org/packages/preferences.
For more features like subpages, hiding of preferences or more widgets look at the example.
According to my research now (I checked the https://pub.dartlang.org and other resources), the answer to your question is, no there is no page like that in Flutter (Check the official documentation). There is one plugin to have SharedPreferences which is from Flutter team, but if you check out its source code, you can see that it just does data modification. Other alternatives from other developers doesn't have anything visual too (I will keep checking, if I find one, I will edit my post).
There are some ways to do it, you can do it by calling android bridge and having android specific screen for only android (yeah I know, it doesn't make much sense) when you are with flutter or my real answer would be you can implement it by using list view as you mentioned and assign different child elements according to your needs.

About ExpansionPanel and SQFlite

Can i make a ExpansionPanel with header and body content from SQFLite database?
this is my code paste.ofcode.org/b8Mns5bSQxqyjX6BwD8DL8 I want to load the header and body from database
You are using ListView.builder to build the List. ListView.builder is meant for building UI widgets.
As it is not attached to the view (it's hanging in initState), ListView.builder will not have iterated once (you can put a print inside and see).
Solution is to use normal list
List.generate(data.length, (index) => new ItemKu(
false,
data[index]["category"],
new Container(
padding: new EdgeInsets.all(10.0),
child: new Text('Hello World'),
)
));

Resources