flutter- I don't know the difference between these two case - flutter

Case 1 :
children: DUMMY_CATEGORIES.map((catData) {
CategoryItem(
catData.title,
catData.color,
);
}).toList(),
Case 2 :
children: DUMMY_CATEGORIES
.map(
(catData) => CategoryItem(
catData.title,
catData.color,
),
)
.toList(),
Case 1 causes an error.
Isn't the two cases the same syntax?
Why is this error occurring?
════════ Exception caught by rendering library ═════════════════════════════
Null check operator used on a null value
The relevant error-causing widget was
GridView
lib\categories_screen.dart:12
═════════════════════════════════════════════════════════════

Case 2 uses the Fat Arrow Expression or Lambda Function Expression, a syntax to write a function on a single line using => syntax AKA fat arrow. more info
DUMMY_CATEGORIES.map(
(catData) => CategoryItem(
catData.title,
catData.color,
),
).toList(),
Fat Arrow Syntax:
(args) => expression
If expression has a return type (in your case, a CategoryItem), it directly returns.
It is the same as your Case 1 with a return statement:
DUMMY_CATEGORIES.map(
(catData) {
return CategoryItem(
catData.title,
catData.color,
),
}
).toList(),

Related

Add event to Multi-Bloc Provider initialization not working

I wanted to add event when initializing bloc inside the 'main.dart'.
But It didn't call init event . Are there any way to do this without calling inside 'initState' of the next class
void main() {
runApp(
MultiBlocProvider(providers: [
BlocProvider(create: (context) => CountlyBloc()..add(CountlyInitEvent()))
], child: MyApp()),
);
}
BHARATH T 's answer is almost correct but you have to set lazy to false not true. Since true means you DO want it to be created lazy. The rest is correct
Just set lazy param inside the BlocProvider as true. By default, the bloc is instantiated only when it is used first. Setting the lazy param to true, forces it to instantiate at the moment.
void main() {
runApp(
MultiBlocProvider(providers: [
BlocProvider(create: (context) => CountlyBloc()..add(CountlyInitEvent()),lazy:true,)
], child: MyApp()),
);
}
Hope it helps! Happy coding:)
MultiBlocProvider( providers: [ BlocProvider(create: (context) => CountlyBloc()..add(CountlyInitEvent()),lazy:false,) ], child: MyApp()),
in order to initialize the bloc instance immediately

VSCode shortcut to select ALL values inside quotes, and then replace a ton of repeated values?

I basically have to modify a 2,000+ line PHP file.
I have to replace all the 'null' values, with the original paremeter with a $ at the start. Now, by manually doing it line by line will take forever. Is there a shortcut or extension I can use to automate this for me?
This is a small block of code which I have:
'SecuredLoanDetails' => array(
'ExitStrategy' => null,
'ChangeOfUseRequired' => null,
'ProjectRequiresPlanning' => null,
'ProjectPlanningGranted' => null,
'BridgingDetails' => array(
'BridgingPaymentMethod' => 'RolledUp',
'PropertyPreviouslyBridged' => null,
'NumberOfMonthsSincePropertyBridged' => null,
'BridgingLoanPurpose' => 'First_Charge',
'OccupiedByClientOrFamilyMember' => null,
'LimitedCompany' => null,
'BridgingPropertyUse' => null,
'BridgingRefurbishmentType' => null,
'BridgingAdditionalPropertiesTotalValue' => null,
'BridgingAdditionalPropertiesTotalOutstanding' => null,
),
),
This is what I want:
'SecuredLoanDetails' => array(
'ExitStrategy' => $ExitStrategy,
'ChangeOfUseRequired' => $ChangeOfUseRequired,
'ProjectRequiresPlanning' => $ProjectRequiresPlanning,
'ProjectPlanningGranted' => $ProjectPlanningGranted,
'BridgingDetails' => array(
'BridgingPaymentMethod' => 'RolledUp',
'PropertyPreviouslyBridged' => $PropertyPreviouslyBridged,
'NumberOfMonthsSincePropertyBridged' => $NumberOfMonthsSincePropertyBridged,
'BridgingLoanPurpose' => 'First_Charge',
'OccupiedByClientOrFamilyMember' => $OccupiedByClientOrFamilyMember,
'LimitedCompany' => $LimitedCompany,
'BridgingPropertyUse' => $BridgingPropertyUse,
'BridgingRefurbishmentType' => $BridgingRefurbishmentType,
'BridgingAdditionalPropertiesTotalValue' => $BridgingAdditionalPropertiesTotalValue,
'BridgingAdditionalPropertiesTotalOutstanding' => $BridgingAdditionalPropertiesTotalOutstanding,
),
),
You can do this with VSCode's find and replace menu. You can enable regex and then use '(\w*)' => null as the find string and '$1' => $$$1 as the replace string.
This works by matching a quoted word followed by => null and capturing the quoted word into the group $1. Then the replacement string is built as '(captured word)' => $(captured word) where (captured word) is the contents of group $1.
Given your text, you can replace (Ctrl + H) the occurrences of 'identifier' => null with 'identifier' => $identifier using the following regex and replace pattern. Make sure to turn on the use of regular expressions in the Find/Replace box (Alt + R or the button on the right side of the Find text field that looks like .*).
('[^']*')(\s*=>\s*)(null)
$1$2\$$1
This captures group 1 'identifier', group 2 =>, and group 3 null and substitutes group 1, group 2, and your variable $identifier.

ChangeNotifierProxyProvider to act as a Selector rather than Consumer

At the moment I have a ChangeNotifierProxyProvider which pulls one value from a normal ChangeNotifierProvider. At the moment, when anything changes in the ChangeNotifierProvider, my ChangeNotifierProxyProvider will be notified and cause a number of other rebuilds from UI's who depend on the ChangeNotifierProxyProvider. Is there a way to only have the ChangeNotifierProxyProvider notified when only a single variable from the ChangeNotifierProvider changes?
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => MainProvider()),
ChangeNotifierProxyProvider<MainProvider, GuideProvider>(
create: (_) => GuideProvider(),
update: (_, mainProvider, guideProvider) {
return guideProvider
..activeState = mainProvider.activeState
..heading = mainProvider.activeState.stateName;
},
),
ChangeNotifierProxyProvider<MainProvider, ExploreProvider>(
create: (_) => ExploreProvider(),
update: (_, mainProvider, exploreProvider) {
return exploreProvider..activeState = mainProvider.activeState;
},
)
],
//update method and other code
);
So in the case above I only want the Explore and Guide providers to update when the variable activeState changes in the MainProvider.

I m trying to fetch order details from website and getting error "A non-null String must be provided to a Text widget'

1.getting error on this line as null
enter code here
return OrderItem(
order: model.myOrders[index],
onRefresh: refreshMyOrders,
);
}),
),
)
You have to check if the indexed order is null and set a default value to protect your code from these types of errors like this:
return OrderItem(
order: model.myOrders[index] ?? 'Default Value',
onRefresh: refreshMyOrders,
);
}),
),
)

How can I avoid charts_flutter DateTime based Series List's runtime type exception?

My model:
class Record {
final DateTime timeStamp;
final int metric;
}
I'd like to display a series of that on the simplest possible LineChart.
List<Record> _sampledRecords;
...
#override
initState() {
_sampledRecords = ...
}
...
child: LineChart(
[
Series<Record, DateTime>(
id: 'Metric 1',
colorFn: (_, __) =>
MaterialPalette.blue.shadeDefault,
domainFn: (Record record, _) => record.timeStamp,
measureFn: (Record record, _) => record.metric,
data: _sampledRecords,
),
],
),
Now this is completely in concert with several example code I saw, like check out https://google.github.io/charts/flutter/example/axes/nonzero_bound_measure_axis
Clearly the headcount is the measurement there (y axis data) and the DateTime is the x axis data. I typed my use-case exactly the same way and the compiler is OK with it.
However runtime I get: type 'List<Series<Record, DateTime>>' is not a subtype of type 'List<Series<dynamic, num>>'. Where does the system pulls this num numeric typing from? I cannot use Receiving runtime error with type 'List<Series<dynamic, dynamic>>' is not a subtype of type 'List<Series<dynamic, num>>' charts_flutter (so please realize my question is NOT a duplicate) solution, because DateTime is not a num type. I tried this as a clarification, but it didn't change anything:
child: LineChart(
<Series<Record, DateTime>>[
Series<Record, DateTime>(
id: 'Metric 1',
colorFn: (_, __) =>
MaterialPalette.blue.shadeDefault,
domainFn: (Record record, _) => record.timeStamp,
measureFn: (Record record, _) => record.metric,
data: _sampledRecords,
),
],
),
I refactored the code like this:
List<Series<Record, DateTime>> _getPowerData() {
return [
Series<Record, DateTime>(
id: 'Metric 1',
colorFn: (_, __) =>
MaterialPalette.blue.shadeDefault,
domainFn: (Record record, _) => record.timeStamp,
measureFn: (Record record, _) => record.power,
data: _sampledRecords,
),
];
}
child: LineChart(_getPowerData()
I get type 'List<Series<dynamic, dynamic>>' is not a subtype of type 'List<Series<dynamic, num>>' runtime exception. Furthermore, I even tried to satisfy the num type with int:
List<Series<Record, int>> _getPowerData() {
return [
Series<Record, int>(
id: 'Metric 1',
colorFn: (_, __) =>
MaterialPalette.blue.shadeDefault,
domainFn: (Record record, _) => record.seconds,
measureFn: (Record record, _) => record.power,
data: _sampledRecords,
),
];
}
But even this yields the type 'List<Series<dynamic, dynamic>>' is not a subtype of type 'List<Series<dynamic, num>>'.
The issue was that the simple LineChart is not geared to handle time series data. Let's take the NonzeroBoundMeasureAxis (https://google.github.io/charts/flutter/example/axes/nonzero_bound_measure_axis) for example: it uses TimeSeriesChart. So I was in a wrestling match with LineChart whereas I should have just picked a more specialized chart (there are multiple) which support time series based data.