Debugging segfault when calling ComputeSignedDistancePairwiseClosestPoints in PyDrake - drake

I'm running an optimization loop that repeatedly calls ComputeSignedDistancePairwiseClosestPoints. After hundreds of cumulative hours of running this without problems, I've encountered a segfault and am looking for guidance on debugging it (or if it's a bug in Drake, possible temporary workarounds).
As suggested in this post, upon initialization, I store diagram, plant, and scene graph contexts, and before calling ComputeSignedDistancePairwiseClosestPoints, I call the query object output port evaluated at the stored scene graph context. Here is a rough outline of the relevant code structure:
class SimplifiedClass:
def __init__(self, ...):
# initializing plant, contexts, and query object port
self.diagram = function_generating_diagram_with_plant(...)
self.plant = self.diagram.GetSubsystemByName("plant")
self.scene_graph = self.diagram.GetSubsystemByName("scene_graph")
_diag_context = self.diagram.CreateDefaultContext()
self.plant_context = self.plant.GetMyMutableContextFromRoot(_diag_context)
self.sg_context = self.scene_graph.GetMyMutableContextFromRoot(_diag_context)
self.qo_port = self.scene_graph.get_query_output_port()
#property
def query_object(self):
return self.qo_port.Eval(self.sg_context)
def function_that_computes_signed_distances(self, ...):
# this function calls ComputeSignedDistancePairClosestPoints()
# it is called repeatedly in an optimization loop
# line that computes signed distance pairs after other operations
sdps = self.query_object.ComputeSignedDistancePairwiseClosestPoints(
max_distance=some_number
)
I can reproduce the segfault by fixing the random seed appropriately, and I find that when changing the max_distance parameter of ComputeSignedDistancePairwiseClosestPoints, the segfault no longer occurs for this specific seed.
I printed a gdb backtrace which returns the following:
#0 0x00007f21a9149be5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#1 0x00007f21a914cc46 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#2 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#3 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#4 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#5 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#6 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#7 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#8 0x00007f21a914cca5 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#9 0x00007f21a914d61b in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#10 0x00007f21a914ba3a in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#11 0x00007f21a914bbdc in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#12 0x00007f21a919f324 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#13 0x00007f21a9165123 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#14 0x00007f21a918961a in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#15 0x00007f21a918d29d in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#16 0x00007f21a918fdd2 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#17 0x00007f21a92a9496 in void drake::geometry::internal::shape_distance::CalcDistanceFallback<double>(fcl::CollisionObject<double> const&, fcl::CollisionObject<double> const&, fcl::DistanceRequest<double> const&, drake::geometry::SignedDistancePair<double>*) () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#18 0x00007f21a92a9aa5 in bool drake::geometry::internal::shape_distance::Callback<double>(fcl::CollisionObject<double>*, fcl::CollisionObject<double>*, void*, double&) ()
from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#19 0x00007f21a91e98ca in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#20 0x00007f21a91e99b2 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#21 0x00007f21a91e998b in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#22 0x00007f21a91e998b in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#23 0x00007f21a91e998b in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#24 0x00007f21a91e99b2 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#25 0x00007f21a91e99b2 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#26 0x00007f21a91e998b in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#27 0x00007f21a91e9a26 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#28 0x00007f21a933a01e in drake::geometry::internal::ProximityEngine<double>::ComputeSignedDistancePairwiseClosestPoints(std::unordered_map<drake::geometry::GeometryId, drake::math::RigidTransform<double>, std::hash<drake::geometry::GeometryId>, std::equal_to<drake::geometry::GeometryId>, std::allocator<std::pair<drake::geometry::GeometryId const, drake::math::RigidTransform<double> > > > const&, double) const ()
from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#29 0x00007f21a93ab1fc in drake::geometry::QueryObject<double>::ComputeSignedDistancePairwiseClosestPoints(double) const () from /opt/drake/lib/python3.10/site-packages/pydrake/common/../../../../libdrake.so
#30 0x00007f20bf6f2327 in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/geometry.cpython-310-x86_64-linux-gnu.so
#31 0x00007f20bf547c4f in ?? () from /opt/drake/lib/python3.10/site-packages/pydrake/geometry.cpython-310-x86_64-linux-gnu.so
#32 0x00005604e39c1b5e in ?? ()
#33 0x00005604e39b87db in _PyObject_MakeTpCall ()
#34 0x00005604e39d066b in ?? ()
#35 0x00005604e39ac2fc in _PyEval_EvalFrameDefault ()
#36 0x00005604e39c23ac in _PyFunction_Vectorcall ()
#37 0x00005604e39ab14a in _PyEval_EvalFrameDefault ()
#38 0x00005604e39d0391 in ?? ()
#39 0x00005604e39ac2fc in _PyEval_EvalFrameDefault ()
#40 0x00005604e39c23ac in _PyFunction_Vectorcall ()
#41 0x00005604e39ab14a in _PyEval_EvalFrameDefault ()
#42 0x00005604e39c23ac in _PyFunction_Vectorcall ()
... (more in this trace omitted since it's not Drake-specific)

Related

Crash in ForEach when deleting element with NavigationView and sheet

Using Xcode 13's new binding variant of ForEach my app crashes predictably on-device (but works in the simulator) when deleting any element other than the last one from content backed by an #Published property.
Strangely, this only happens when the view is contained within a NavigationView and has a sheet attached.
Here is a self-contained app demonstrating the issue:
import SwiftUI
struct Vegetable: Identifiable {
let id: UUID
let name: String
}
class MyModel: ObservableObject {
#Published var vegetables: [Vegetable] = [
Vegetable(id: UUID(), name: "Eggplant"),
Vegetable(id: UUID(), name: "Corn"),
Vegetable(id: UUID(), name: "Radish")
]
}
#main
struct SwiftUIForEachTestApp: App {
#StateObject var model = MyModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(model)
}
}
}
struct ContentView: View {
var body: some View {
// Remove the containing NavigationView and the crash disappears
NavigationView {
MyView()
}
}
}
struct MyView: View {
#EnvironmentObject private var model: MyModel
#State private var isPresentingSheet = false
var body: some View {
List {
ForEach($model.vegetables) { $vegetable in
Text(vegetable.name)
}
.onDelete { indices in model.vegetables.remove(atOffsets: indices) }
}
// Remove the sheet and the crash disappears
.sheet(isPresented: $isPresentingSheet) {
}
}
}
Running the app and deleting the top row results in the following crash (line 16 corresponds to #main):
#0 0x00000001a73a6eac in _swift_runtime_on_report ()
#1 0x00000001a741f100 in _swift_stdlib_reportFatalErrorInFile ()
#2 0x00000001a705e668 in closure #1 in closure #1 in closure #1 in _assertionFailure(_:_:file:line:flags:) ()
#3 0x00000001a705dce0 in _assertionFailure(_:_:file:line:flags:) ()
#4 0x00000001a703c6b4 in _ArrayBuffer._checkInoutAndNativeTypeCheckedBounds(_:wasNativeTypeChecked:) ()
#5 0x00000001a7041e2c in Array.subscript.read ()
#6 0x00000001a7041d58 in protocol witness for Collection.subscript.read in conformance [τ_0_0] ()
#7 0x0000000100320c38 in closure #1 in ForEach<>.init<τ_0_0>(_:id:content:) ()
#8 0x0000000100320f48 in partial apply for closure #1 in ForEach<>.init<τ_0_0>(_:id:content:) ()
#9 0x0000000100320fd8 in thunk for #escaping #callee_guaranteed (#in_guaranteed τ_1_0.Collection.Index) -> (#out τ_1_0.Collection.Index, #out τ_0_1) ()
#10 0x0000000100321090 in partial apply for thunk for #escaping #callee_guaranteed (#in_guaranteed τ_1_0.Collection.Index) -> (#out τ_1_0.Collection.Index, #out τ_0_1) ()
#11 0x00000001a7193d0c in LazyMapSequence<>.subscript.read ()
#12 0x00000001a71938e4 in protocol witness for Collection.subscript.read in conformance <> LazyMapSequence<τ_0_0, τ_0_1> ()
#13 0x00000001aa2a374c in ForEach.IDGenerator.makeID(data:index:offset:) ()
#14 0x00000001aa2abf54 in ForEachState.ForEachViewIDCollection.subscript.getter ()
#15 0x00000001aa2ac914 in ForEachState.ForEachViewIDCollection.subscript.read ()
#16 0x00000001aa2ac84c in protocol witness for Collection.subscript.read in conformance ForEachState<τ_0_0, τ_0_1, τ_0_2>.ForEachViewIDCollection ()
#17 0x00000001aa37a838 in _ViewList_ID._Views.subscript.getter ()
#18 0x00000001aa37a3f4 in protocol witness for Collection.subscript.read in conformance _ViewList_ID.Views ()
#19 0x00000001a71eaecc in Slice.subscript.getter ()
#20 0x00000001a71ed008 in Slice.subscript.read ()
#21 0x00000001a71ecf48 in protocol witness for Collection.subscript.read in conformance Slice<τ_0_0> ()
#22 0x00000001a7193cc8 in LazyMapSequence<>.subscript.read ()
#23 0x00000001a71938e4 in protocol witness for Collection.subscript.read in conformance <> LazyMapSequence<τ_0_0, τ_0_1> ()
#24 0x00000001aa157f44 in ShadowRowCollection.subscript.getter ()
#25 0x00000001aa1580ec in ShadowRowCollection.subscript.read ()
#26 0x00000001aa15802c in protocol witness for Collection.subscript.read in conformance ShadowRowCollection<τ_0_0> ()
#27 0x00000001aa365448 in ListCoreDataSource.rowID(at:) ()
#28 0x00000001aa004ec0 in closure #1 in performUpdates #1 <τ_0_0, τ_0_1>() in ListCoreCoordinator.updateUITableView(_:to:transaction:) ()
#29 0x00000001a9ffd09c in specialized _ArrayProtocol.filter(_:) ()
#30 0x00000001aa004658 in performUpdates #1 <τ_0_0, τ_0_1>() in ListCoreCoordinator.updateUITableView(_:to:transaction:) ()
#31 0x00000001aa00565c in closure #1 in ListCoreCoordinator.updateUITableView(_:to:transaction:) ()
#32 0x00000001a9ec6008 in thunk for #escaping #callee_guaranteed () -> () ()
#33 0x00000001a9eaee84 in static Update.end() ()
#34 0x00000001a9cd7390 in static NSRunLoop.flushObservers() ()
#35 0x00000001a9cd72d8 in closure #1 in closure #1 in static NSRunLoop.addObserver(_:) ()
#36 0x00000001a9cd2250 in specialized thunk for #callee_guaranteed () -> (#error #owned Error) ()
#37 0x00000001c9b53f24 in autoreleasepool<τ_0_0>(invoking:) ()
#38 0x00000001a9cd72b8 in closure #1 in static NSRunLoop.addObserver(_:) ()
#39 0x00000001a9cd7410 in #objc closure #1 in static NSRunLoop.addObserver(_:) ()
#40 0x00000001a3437588 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ ()
#41 0x00000001a34316ac in __CFRunLoopDoObservers ()
#42 0x00000001a3431c58 in __CFRunLoopRun ()
#43 0x00000001a3431308 in CFRunLoopRunSpecific ()
#44 0x00000001baab4734 in GSEventRunModal ()
#45 0x00000001a5eaf75c in -[UIApplication _run] ()
#46 0x00000001a5eb4fcc in UIApplicationMain ()
#47 0x00000001aa39c380 in closure #1 in KitRendererCommon(_:) ()
#48 0x00000001aa39c30c in runApp<τ_0_0>(_:) ()
#49 0x00000001a9e94b38 in static App.main() ()
#50 0x000000010031c9c4 in static SwiftUIForEachTestApp.$main() at /xxx/SwiftUIForEachTest/Shared/ContentView.swift:16
#51 0x000000010031e888 in main ()
#52 0x00000001a30edcf8 in start ()
Is this a bug in SwiftUI?
works very well for me on macos 12.beta, xcode 13.beta, target ios 15 and macCatalyst.
Tested on mac, iPhone and iPad. Maybe it is different on older systems.
EDIT: using EnvironmentObject, this is the code I'm using in my tests:
import SwiftUI
#main
struct TestApp: App {
#StateObject var model = MyModel() // <---
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(model)
}
}
}
struct ContentView: View {
#EnvironmentObject var model: MyModel // <---
var body: some View {
NavigationView {
MyView()
}
}
}
struct MyView: View {
#EnvironmentObject var model: MyModel // <---
#State private var isPresentingSheet = false
var body: some View {
List {
ForEach($model.vegetables) { $vegetable in
Text(vegetable.name)
}
.onDelete { indices in model.vegetables.remove(atOffsets: indices) }
}
.sheet(isPresented: $isPresentingSheet) {
Text("the sheet") // <----
}
}
}
struct Vegetable: Identifiable {
let id: UUID
let name: String
}
class MyModel: ObservableObject {
#Published var vegetables: [Vegetable] = [
Vegetable(id: UUID(), name: "Eggplant"),
Vegetable(id: UUID(), name: "Corn"),
Vegetable(id: UUID(), name: "Radish")
]
}

Call to undefined method Laravel\Lumen\Routing\Router::dispatch()

Does anyone know how to fix this?
I tried to use these codes for issuing access token, but i got errored.
protected function oauthLogin(Request $request)
{
$client = DB::table('oauth_clients')
->where('password_client', true)
->first();
$request->request->add([
"grant_type" => "password",
"username" => $request->email,
"password" => $request->password,
"client_id" => $client->id,
"client_secret" => $client->secret,
]);
$tokenRequest = $request->create(
env('APP_URL') . 'api/v1/oauth/token',
'post'
);
$instance = Route::dispatch($tokenRequest);
return json_decode($instance->getContent());
}
This was the error traceable logs. I dont know if this is related because my even my credentials was correct so, i dont think, that my credentials was denied. I tried it also to oauth/token and it was working. Still the same error. I've got.
[2019-02-20 13:22:09] local.ERROR: League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in D:\laragon\www\auth-service-optimize\vendor\league\oauth2-server\src\Exception\OAuthServerException.php:215
Stack trace:
#0 D:\laragon\www\auth-service-optimize\vendor\league\oauth2-server\src\AuthorizationValidators\BearerTokenValidator.php(73): League\OAuth2\Server\Exception\OAuthServerException::accessDenied('Access token co...')
#1 D:\laragon\www\auth-service-optimize\vendor\league\oauth2-server\src\ResourceServer.php(84): League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator->validateAuthorization(Object(Zend\Diactoros\ServerRequest))
#2 D:\laragon\www\auth-service-optimize\vendor\laravel\passport\src\Guards\TokenGuard.php(174): League\OAuth2\Server\ResourceServer->validateAuthenticatedRequest(Object(Zend\Diactoros\ServerRequest))
#3 D:\laragon\www\auth-service-optimize\vendor\laravel\passport\src\Guards\TokenGuard.php(126): Laravel\Passport\Guards\TokenGuard->getPsrRequestViaBearerToken(Object(Laravel\Lumen\Http\Request))
#4 D:\laragon\www\auth-service-optimize\vendor\laravel\passport\src\Guards\TokenGuard.php(89): Laravel\Passport\Guards\TokenGuard->authenticateViaBearerToken(Object(Laravel\Lumen\Http\Request))
#5 D:\laragon\www\auth-service-optimize\vendor\laravel\passport\src\PassportServiceProvider.php(274): Laravel\Passport\Guards\TokenGuard->user(Object(Laravel\Lumen\Http\Request))
#6 [internal function]: Laravel\Passport\PassportServiceProvider->Laravel\Passport\{closure}(Object(Laravel\Lumen\Http\Request), NULL)
#7 D:\laragon\www\auth-service-optimize\vendor\illuminate\auth\RequestGuard.php(58): call_user_func(Object(Closure), Object(Laravel\Lumen\Http\Request), NULL)
#8 D:\laragon\www\auth-service-optimize\app\Http\Controllers\AuthController.php(169): Illuminate\Auth\RequestGuard->user()
#9 [internal function]: App\Http\Controllers\AuthController->adminLogin(Object(Laravel\Lumen\Http\Request))
#10 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(29): call_user_func_array(Array, Array)
#11 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#12 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Laravel\Lumen\Application), Array, Object(Closure))
#13 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\Container.php(572): Illuminate\Container\BoundMethod::call(Object(Laravel\Lumen\Application), Array, Array, NULL)
#14 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(378): Illuminate\Container\Container->call(Array, Array)
#15 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(344): Laravel\Lumen\Application->callControllerCallable(Array, Array)
#16 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(318): Laravel\Lumen\Application->callLumenController(Object(App\Http\Controllers\AuthController), 'adminLogin', Array)
#17 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(280): Laravel\Lumen\Application->callControllerAction(Array)
#18 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(265): Laravel\Lumen\Application->callActionOnArrayBasedRoute(Array)
#19 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(165): Laravel\Lumen\Application->handleFoundRoute(Array)
#20 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(418): Laravel\Lumen\Application->Laravel\Lumen\Concerns\{closure}(Object(Laravel\Lumen\Http\Request))
#21 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(171): Laravel\Lumen\Application->sendThroughPipeline(Array, Object(Closure))
#22 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(108): Laravel\Lumen\Application->dispatch(NULL)
#23 D:\laragon\www\auth-service-optimize\public\index.php(28): Laravel\Lumen\Application->run()
#24 {main} {"exception":"[object] (League\\OAuth2\\Server\\Exception\\OAuthServerException(code: 9): The resource owner or authorization server denied the request. at D:\\laragon\\www\\auth-service-optimize\\vendor\\league\\oauth2-server\\src\\Exception\\OAuthServerException.php:215)
[stacktrace]
#0 D:\\laragon\\www\\auth-service-optimize\\vendor\\league\\oauth2-server\\src\\AuthorizationValidators\\BearerTokenValidator.php(73): League\\OAuth2\\Server\\Exception\\OAuthServerException::accessDenied('Access token co...')
#1 D:\\laragon\\www\\auth-service-optimize\\vendor\\league\\oauth2-server\\src\\ResourceServer.php(84): League\\OAuth2\\Server\\AuthorizationValidators\\BearerTokenValidator->validateAuthorization(Object(Zend\\Diactoros\\ServerRequest))
#2 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\passport\\src\\Guards\\TokenGuard.php(174): League\\OAuth2\\Server\\ResourceServer->validateAuthenticatedRequest(Object(Zend\\Diactoros\\ServerRequest))
#3 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\passport\\src\\Guards\\TokenGuard.php(126): Laravel\\Passport\\Guards\\TokenGuard->getPsrRequestViaBearerToken(Object(Laravel\\Lumen\\Http\\Request))
#4 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\passport\\src\\Guards\\TokenGuard.php(89): Laravel\\Passport\\Guards\\TokenGuard->authenticateViaBearerToken(Object(Laravel\\Lumen\\Http\\Request))
#5 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\passport\\src\\PassportServiceProvider.php(274): Laravel\\Passport\\Guards\\TokenGuard->user(Object(Laravel\\Lumen\\Http\\Request))
#6 [internal function]: Laravel\\Passport\\PassportServiceProvider->Laravel\\Passport\\{closure}(Object(Laravel\\Lumen\\Http\\Request), NULL)
#7 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\auth\\RequestGuard.php(58): call_user_func(Object(Closure), Object(Laravel\\Lumen\\Http\\Request), NULL)
#8 D:\\laragon\\www\\auth-service-optimize\\app\\Http\\Controllers\\AuthController.php(169): Illuminate\\Auth\\RequestGuard->user()
#9 [internal function]: App\\Http\\Controllers\\AuthController->adminLogin(Object(Laravel\\Lumen\\Http\\Request))
#10 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(29): call_user_func_array(Array, Array)
#11 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#12 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Laravel\\Lumen\\Application), Array, Object(Closure))
#13 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\Container.php(572): Illuminate\\Container\\BoundMethod::call(Object(Laravel\\Lumen\\Application), Array, Array, NULL)
#14 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(378): Illuminate\\Container\\Container->call(Array, Array)
#15 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(344): Laravel\\Lumen\\Application->callControllerCallable(Array, Array)
#16 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(318): Laravel\\Lumen\\Application->callLumenController(Object(App\\Http\\Controllers\\AuthController), 'adminLogin', Array)
#17 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(280): Laravel\\Lumen\\Application->callControllerAction(Array)
#18 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(265): Laravel\\Lumen\\Application->callActionOnArrayBasedRoute(Array)
#19 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(165): Laravel\\Lumen\\Application->handleFoundRoute(Array)
#20 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(418): Laravel\\Lumen\\Application->Laravel\\Lumen\\Concerns\\{closure}(Object(Laravel\\Lumen\\Http\\Request))
#21 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(171): Laravel\\Lumen\\Application->sendThroughPipeline(Array, Object(Closure))
#22 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(108): Laravel\\Lumen\\Application->dispatch(NULL)
#23 D:\\laragon\\www\\auth-service-optimize\\public\\index.php(28): Laravel\\Lumen\\Application->run()
#24 {main}
"}
[2019-02-20 13:22:09] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Laravel\Lumen\Routing\Router::dispatch() in D:\laragon\www\auth-service-optimize\vendor\illuminate\support\Facades\Facade.php:237
Stack trace:
#0 D:\laragon\www\auth-service-optimize\app\Http\Controllers\AuthController.php(202): Illuminate\Support\Facades\Facade::__callStatic('dispatch', Array)
#1 D:\laragon\www\auth-service-optimize\app\Http\Controllers\AuthController.php(171): App\Http\Controllers\AuthController->oauthLogin(Object(Laravel\Lumen\Http\Request))
#2 [internal function]: App\Http\Controllers\AuthController->adminLogin(Object(Laravel\Lumen\Http\Request))
#3 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(29): call_user_func_array(Array, Array)
#4 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#5 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Laravel\Lumen\Application), Array, Object(Closure))
#6 D:\laragon\www\auth-service-optimize\vendor\illuminate\container\Container.php(572): Illuminate\Container\BoundMethod::call(Object(Laravel\Lumen\Application), Array, Array, NULL)
#7 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(378): Illuminate\Container\Container->call(Array, Array)
#8 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(344): Laravel\Lumen\Application->callControllerCallable(Array, Array)
#9 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(318): Laravel\Lumen\Application->callLumenController(Object(App\Http\Controllers\AuthController), 'adminLogin', Array)
#10 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(280): Laravel\Lumen\Application->callControllerAction(Array)
#11 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(265): Laravel\Lumen\Application->callActionOnArrayBasedRoute(Array)
#12 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(165): Laravel\Lumen\Application->handleFoundRoute(Array)
#13 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(418): Laravel\Lumen\Application->Laravel\Lumen\Concerns\{closure}(Object(Laravel\Lumen\Http\Request))
#14 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(171): Laravel\Lumen\Application->sendThroughPipeline(Array, Object(Closure))
#15 D:\laragon\www\auth-service-optimize\vendor\laravel\lumen-framework\src\Concerns\RoutesRequests.php(108): Laravel\Lumen\Application->dispatch(NULL)
#16 D:\laragon\www\auth-service-optimize\public\index.php(28): Laravel\Lumen\Application->run()
#17 {main} {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to undefined method Laravel\\Lumen\\Routing\\Router::dispatch() at D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\support\\Facades\\Facade.php:237)
[stacktrace]
#0 D:\\laragon\\www\\auth-service-optimize\\app\\Http\\Controllers\\AuthController.php(202): Illuminate\\Support\\Facades\\Facade::__callStatic('dispatch', Array)
#1 D:\\laragon\\www\\auth-service-optimize\\app\\Http\\Controllers\\AuthController.php(171): App\\Http\\Controllers\\AuthController->oauthLogin(Object(Laravel\\Lumen\\Http\\Request))
#2 [internal function]: App\\Http\\Controllers\\AuthController->adminLogin(Object(Laravel\\Lumen\\Http\\Request))
#3 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(29): call_user_func_array(Array, Array)
#4 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#5 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Laravel\\Lumen\\Application), Array, Object(Closure))
#6 D:\\laragon\\www\\auth-service-optimize\\vendor\\illuminate\\container\\Container.php(572): Illuminate\\Container\\BoundMethod::call(Object(Laravel\\Lumen\\Application), Array, Array, NULL)
#7 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(378): Illuminate\\Container\\Container->call(Array, Array)
#8 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(344): Laravel\\Lumen\\Application->callControllerCallable(Array, Array)
#9 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(318): Laravel\\Lumen\\Application->callLumenController(Object(App\\Http\\Controllers\\AuthController), 'adminLogin', Array)
#10 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(280): Laravel\\Lumen\\Application->callControllerAction(Array)
#11 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(265): Laravel\\Lumen\\Application->callActionOnArrayBasedRoute(Array)
#12 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(165): Laravel\\Lumen\\Application->handleFoundRoute(Array)
#13 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(418): Laravel\\Lumen\\Application->Laravel\\Lumen\\Concerns\\{closure}(Object(Laravel\\Lumen\\Http\\Request))
#14 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(171): Laravel\\Lumen\\Application->sendThroughPipeline(Array, Object(Closure))
#15 D:\\laragon\\www\\auth-service-optimize\\vendor\\laravel\\lumen-framework\\src\\Concerns\\RoutesRequests.php(108): Laravel\\Lumen\\Application->dispatch(NULL)
#16 D:\\laragon\\www\\auth-service-optimize\\public\\index.php(28): Laravel\\Lumen\\Application->run()
#17 {main}
"}
The request that is dispatched is without the credentials added in the preceding line.
The reason being that Request::create returns a new request instance.
Add the request parameters in the newly created on $request and then dispatch it.
$tokenRequest = $request->create(
env('APP_URL') . 'api/v1/oauth/token',
'POST'
);
$tokenRequest->request->add([
"grant_type" => "password",
"username" => $request->email,
"password" => $request->password,
"client_id" => $client->id,
"client_secret" => $client->secret,
]);
$response = app()->handle($tokenRequest);

type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic> Flutter

I am using Event Channels in Flutter to return beacon data from Native SDK to Flutter. This was working fine until a recent Flutter upgrade.Now, I am getting the following error.
type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic>
with the following stack trace:
#0 _registerErrorHandler (dart:async/async_error.dart:22:60)
#1 _BufferingStreamSubscription.onError (dart:async/stream_impl.dart:146:16)
#2 new _BufferingStreamSubscription (dart:async/stream_impl.dart:113:10)
#3 new _ControllerSubscription (dart:async/stream_controller.dart)
#4 new _BroadcastSubscription (dart:async/broadcast_stream_controller.dart)
#5 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:212:46)
#6 _ControllerStream._createSubscription (dart:async/stream_controller.dart:817:19)
#7 _StreamImpl.listen (dart:async/stream_impl.dart:466:9)
#8 _MyHomePageState.initPlatformState.<anonymous closure>.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:95:43)
#9 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#10 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#12 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#13 Future._complete (dart:async/future_impl.dart:467:7)
#14 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#15 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart)
<asynchronous suspension>
#16 _MyHomePageState.initPlatformState.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:89:24)
<asynchronous suspension>
#17 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#18 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#19 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#20 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#21 Future._complete (dart:async/future_impl.dart:467:7)
#22 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#23 User_Profile.getUser (package:flutter_poc/Models/User.dart)
<asynchronous suspension>
#24 _MyHomePageState.initPlatformState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:69:24)
<asynchronous suspension>
#25 _MyHomePageState.initState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:52:5)
#26 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
#27 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
#28 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
#29 Element.updateChild
This is my EventChannel implementation:
static const platform = const MethodChannel('samples.flutter.io/initialiseRanging');
static const stream =
const EventChannel('samples.flutter.io/ranging');
try {
await platform.invokeMethod('initialiseRanging').then((result){
print(result);
setState(() {
_currentValue = result;
});
stream.receiveBroadcastStream().listen(_onEvent, onError: _onError);
});
} on PlatformException catch (e) {
print( "{e.message}");
}
This is how the _onEvent and _onError functions are implemented.
void _onEvent(Object event) {
setState(() {
_currentValue = event.toString();
});
print(event);
}
void _onError(PlatformException error) {
print(error);
}
Any idea on why this could possible happen?
void _onError(PlatformException error) {
should be
void _onError(Object error) {
Even when you are only interested in PlatformException or even when this is the only exception that happened so far, doesn't mean there can't be others. The expected handler function needs to match the parameter type, instead of only the exceptions you expect.

EXC_BAD_ACCESS when safely unwrapping optional on NSManagedObject

I have the following base NSManagedObject in our Application:
#objc(LaravelEntity)
class LaravelEntity: NSManagedObject {
static func create(moc: NSManagedObjectContext) -> LaravelEntity? {
let entityName = NSStringFromClass(self)
let ent = NSEntityDescription.insertNewObject(forEntityName: entityName, into: moc) as? LaravelEntity
// We set local changes to true, so it will definitely be pushed to the server
ent?.local_changes = true
return ent
}
static func lastUpdatedRequest() -> NSFetchRequest<LaravelEntity> {
let request : NSFetchRequest<LaravelEntity> = self.self.fetchRequest()
let sort = NSSortDescriptor(key: #keyPath(LaravelEntity.updated_at), ascending: false)
request.sortDescriptors = [sort]
request.fetchLimit = 1
return request
}
}
I also have some subclasses of this. They are defined as subclasses in the DataModel as well:
#objc(Answer)
class Answer: LaravelEntity {
}
I try to fetch the last updated entity for a given class like this:
func lastUpdated(klass: LaravelEntity.Type, ctx : NSManagedObjectContext? = nil) -> LaravelEntity? {
do {
let request = klass.lastUpdatedRequest()
let result = try ctx?.fetch(request) ?? self.persistentContainer.newBackgroundContext().fetch(request)
return result.first
} catch {
print("Error while fetching last updated: \(error)!")
}
return nil
}
This works great for the most part. However, sporadically the application just crashes when trying to do something as simple as querying the id: lastUpdated?.id == 1. I have no idea why this would crash, as all optionals are safely handled (as far as I can tell). Also, when looking at the objects in the debugger, they display fine (e.g. po lastUpdated?.id == 1 returns true in the debugger).
I have created the following example test case to reproduce the problem, somewhat consistently:
func testLastUpdated() {
for i in 0...1000 {
let cases = [Location.self, Position.self, Answer.self, Question.self]
for kase in cases {
let old = kase.create(moc: sm.persistentContainer.viewContext)
let new = kase.create(moc: sm.persistentContainer.viewContext)
XCTAssert(old != nil, "Couldn't create old \(kase) object!")
XCTAssert(new != nil, "Couldn't create new \(kase) object!")
old?.updated_at = Date(timeIntervalSinceNow: TimeInterval(-60*60*24 + i * 60))
old?.id = Int32(i*2)
new?.updated_at = Date(timeIntervalSinceNow: TimeInterval(i*60))
new?.id = Int32(i*2+1)
try! sm.persistentContainer.viewContext.save()
let last_updated = sm.lastUpdated(klass: kase)
XCTAssert(last_updated?.id == new?.id, "Last updated \(kase) doesn't have the correct id \(last_updated?.id ?? -1) vs \(new?.id ?? -1)!") //It crashes on this line.
}
}
}
However, even with a 1000 repetitions, it only crashes about 1/3 of the time I run the test. Additionally, it only crashes in the low 50s of iterations.
The following is the callstack when running the above test:
#0 0x00000001857f8430 in objc_msgSend ()
#1 0x0000000188e1f274 in -[NSPersistentStoreCoordinator _canRouteToStore:forContext:] ()
#2 0x0000000188e21f38 in __110-[NSPersistentStoreCoordinator(_NSInternalMethods) newValueForRelationship:forObjectWithID:withContext:error:]_block_invoke ()
#3 0x0000000188e29af0 in gutsOfBlockToNSPersistentStoreCoordinatorPerform ()
#4 0x0000000185f19048 in _dispatch_client_callout ()
#5 0x0000000185f5b760 in _dispatch_sync_invoke_and_complete_recurse ()
#6 0x0000000185f5b26c in _dispatch_sync_wait ()
#7 0x0000000188e17f74 in _perform ()
#8 0x0000000188e17d2c in -[NSPersistentStoreCoordinator _routeLightweightBlock:toStore:] ()
#9 0x0000000188d4bc94 in -[NSPersistentStoreCoordinator(_NSInternalMethods) newValueForRelationship:forObjectWithID:withContext:error:] ()
#10 0x0000000188d34d7c in _PFFaultHandlerFulfillFault ()
#11 0x0000000188d32a80 in _PFFaultHandlerLookupRow ()
#12 0x0000000188d32334 in _PF_FulfillDeferredFault ()
#13 0x0000000188dd7644 in _pvfk_header ()
#14 0x0000000188dd7450 in _sharedIMPL_pvfk_core_i ()
#15 0x00000001092484a4 in implicit closure #5 in SyncManagerTests.testLastUpdated() at CDTests.swift:74
#16 0x00000001092589d4 in partial apply for implicit closure #5 in SyncManagerTests.testLastUpdated() ()
#17 0x00000001092a5bdc in partial apply for closure #1 in XCTAssertTrue(_:_:file:line:) ()
#18 0x00000001092a5448 in partial apply for closure #1 in _XCTRunThrowableBlock(_:) ()
#19 0x0000000109290224 in thunk for #callee_owned () -> () ()
#20 0x00000001092a6048 in _XCTRunThrowableBlockBridge ()
#21 0x00000001092943bc in specialized _XCTRunThrowableBlock(_:) ()
#22 0x0000000109296118 in specialized XCTAssertTrue(_:_:file:line:) ()
#23 0x000000010929045c in XCTAssert(_:_:file:line:) ()
#24 0x0000000109248010 in SyncManagerTests.testLastUpdated() at CDTests.swift:74
#25 0x0000000109248aa8 in #objc SyncManagerTests.testLastUpdated() ()
#26 0x000000018659d670 in __invoking___ ()
#27 0x000000018647c6cc in -[NSInvocation invoke] ()
#28 0x0000000107996654 in __24-[XCTestCase invokeTest]_block_invoke.275 ()
#29 0x00000001079e4208 in -[XCTMemoryChecker _assertInvalidObjectsDeallocatedAfterScope:] ()
#30 0x0000000107996404 in __24-[XCTestCase invokeTest]_block_invoke ()
#31 0x00000001079dc9d8 in -[XCUITestContext performInScope:] ()
#32 0x000000010799614c in -[XCTestCase invokeTest] ()
#33 0x0000000107997224 in __26-[XCTestCase performTest:]_block_invoke.382 ()
#34 0x00000001079e1a78 in +[XCTContext runInContextForTestCase:block:] ()
#35 0x0000000107996c20 in -[XCTestCase performTest:] ()
#36 0x0000000107992e14 in __27-[XCTestSuite performTest:]_block_invoke ()
#37 0x000000010799283c in -[XCTestSuite _performProtectedSectionForTest:testSection:] ()
#38 0x0000000107992a4c in -[XCTestSuite performTest:] ()
#39 0x0000000107992e14 in __27-[XCTestSuite performTest:]_block_invoke ()
#40 0x000000010799283c in -[XCTestSuite _performProtectedSectionForTest:testSection:] ()
#41 0x0000000107992a4c in -[XCTestSuite performTest:] ()
#42 0x0000000107992e14 in __27-[XCTestSuite performTest:]_block_invoke ()
#43 0x000000010799283c in -[XCTestSuite _performProtectedSectionForTest:testSection:] ()
#44 0x0000000107992a4c in -[XCTestSuite performTest:] ()
#45 0x00000001079eb484 in __44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke ()
#46 0x00000001079a5994 in -[XCTestObservationCenter _observeTestExecutionForBlock:] ()
#47 0x00000001079eb300 in -[XCTTestRunSession runTestsAndReturnError:] ()
#48 0x00000001079823d4 in -[XCTestDriver runTestsAndReturnError:] ()
#49 0x00000001079e0c20 in _XCTestMain ()
#50 0x000000018653e0fc in __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ ()
#51 0x000000018653d9cc in __CFRunLoopDoBlocks ()
#52 0x000000018653b6dc in __CFRunLoopRun ()
#53 0x000000018645bfb8 in CFRunLoopRunSpecific ()
#54 0x00000001882f3f84 in GSEventRunModal ()
#55 0x000000018fa302e8 in UIApplicationMain ()
#56 0x000000010137f528 in main at AppDelegate.swift:13
#57 0x0000000185f7e56c in start ()
I have no idea what could cause such a crash, since all optionals are handled correctly.
Edit 1: So the crash definitely happens on the following line last_updated?.id == new?.id (Which still doesn't make any sense to me). Even if I comment out all code changing the objects and only create one object, it still crashes (randomly) on lastUpdated?.id != nil.
Core data is not thread safe. Every context has one and only one thread that is can be read or written from. If you violate this, the behavior is UNDEFINED. Which means that it may crash or it may not. It may wait for 10 minutes and then crash when you do something unrelated.
In your code you are creating a newBackgroundContext inside func lastUpdated (because you are passing a nil context). Doing a fetch with this context is illegal. You can only use this context with performBlock or performBlockAndWait.
Also you have an extra self. in lastUpdatedRequest

Firebase (Dart) future exception

I am trying to use firebase package to see if I can use it with my app | https://pub.dartlang.org/packages/firebase
I am trying to covert this code in Javascript
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
taken from https://www.firebase.com/docs/web/guide/saving-data.html#section-transactions
My attempt in dart is:
int getMrn() {
var testRef = firebaseClient.child('mrn');
return testRef.transaction((curVal) {
return curVal == null ? 1 : curVal + 1;
}).then((result) {
var snapshot = result.snapshot;
print( snapshot.val());
});
}
The correct curVal is returned and the mrn is written correctly to the database. Also the correct value is printed.
However, I get the following error and I am uncertain why:
Exception: Uncaught Error: type '_Future' is not a subtype of type 'int' of 'function result'.
Stack Trace:
#0 getMrn (package:epimss_db/firebase_db.dart:26:15)
#1 onMenuItemSelected (package:epimss_lab/components/chempath/nephrology/electrolytes_rqst_form.dart:116:17)
#2 Function.apply (dart:core-patch/function_patch.dart:28)
#3 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#4 invoke (package:smoke/smoke.dart:43:41)
#5 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#6 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#7 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#8 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#9 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
#10 BlinkEventTarget.dispatchEvent_Callback_1 (dart:_blink:7764)
#11 BlinkEventTarget.dispatchEvent_Callback_1_ (dart:_blink:7765)
#12 EventTarget.dispatchEvent (dart:html:14741)
#13 onMainActionClicked (package:html_components/menu/split_button.dart:34:23)
#14 Function.apply (dart:core-patch/function_patch.dart:28)
#15 GeneratedObjectAccessorService.invoke (package:smoke/static.dart:149:28)
#16 invoke (package:smoke/smoke.dart:43:41)
#17 HtmlElement&Polymer.dispatchMethod (package:polymer/src/instance.dart:1054:19)
#18 BindingDelegate&PolymerEventBindings.getEventHandler.<anonymous closure> (package:polymer/src/events.dart:82:32)
#19 _RootZone.runUnaryGuarded (dart:async/zone.dart:1093)
#20 _RootZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1122)
#21 BindingDelegate&PolymerEventBindings.prepareEventBinding.<anonymous closure>.<anonymous closure> (package:polymer/src/events.dart:101:67)
1
Thanks
Future<int> getMrn() { // <== 3
var testRef = firebaseClient.child('mrn');
return testRef.transaction((curVal) { // <== 2)
return curVal == null ? 1 : curVal + 1;
}).then((result) {
var snapshot = result.snapshot;
print( snapshot.val());
return result; // <== 1)
});
}
1) The value returned from the last chained then() is returned at 2)
3) Because this is async code a Future<int> is returned instead of int.
You call this code like
getMrn().then((result) {
// doSomething with the code here
});
or with await
void someFunc() async { // <== async necessary in order to be able to use await
var result = await getMrn();
}

Resources