问:
Executing/Running Flutter App in Background
right now I'm working on a project, where I'm sending data from a microcontroller (ESP32) to my Flutter App via BLE. When one value of the data is greater than a defined limit, a sound is played, and then stopped, when its lower than the limit.
Now the problem: If the App is in "background-mode", the Dart Code won't be executed.
If tried to solve the problem, with the android-alarm-manager plugin or the WidgetBindingObserver, but couldn't find a proper solution.

My main.dart file:

```<code>// Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_app_2/werte.dart';
import 'package:flutter_blue_app_2/widgets.dart';
import 'package:flutter_blue/flutter_blue.dart';

void main() {
  runApp(FlutterBlueApp());
}

class FlutterBlueApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      color: Colors.lightBlue,
      home: StreamBuilder<BluetoothState>(
          stream: FlutterBlue.instance.state,
          initialData: BluetoothState.unknown,
          builder: (c, snapshot) {
            final state = snapshot.data;
            if (state == BluetoothState.on) {
              return FindDevicesScreen();
            }
            return BluetoothOffScreen(state: state);
          }),
    );
  }
}

class BluetoothOffScreen extends StatelessWidget {
  const BluetoothOffScreen({Key key, this.state}) : super(key: key);
  final BluetoothState state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Icon(
              Icons.bluetooth_disabled,
              size: 200.0,
              color: Colors.white54,
            ),
            Text(
              "BLUETOOTH ADAPTER IS ${state.toString().substring(15)}.",
              style: Theme.of(context)
                  .primaryTextTheme
                  .subhead
                  .copyWith(color: Colors.white),
            ),
          ],
        ),
      ),
    );
  }
}

class FindDevicesScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FIND DEVICES ..."),
      ),
      body: RefreshIndicator(
        onRefresh: () =>
            FlutterBlue.instance.startScan(timeout: Duration(seconds: 4)),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              StreamBuilder<List<BluetoothDevice>>(
                stream: Stream.periodic(Duration(seconds: 2))
                    .asyncMap((_) => FlutterBlue.instance.connectedDevices),
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map((d) => ListTile(
                            title: Text(d.name),
                            subtitle: Text(d.id.toString()),
                            trailing: StreamBuilder<BluetoothDeviceState>(
                              stream: d.state,
                              initialData: BluetoothDeviceState.disconnected,
                              builder: (c, snapshot) {
                                if (snapshot.data ==
                                    BluetoothDeviceState.connected) {
                                  return RaisedButton(
                                    child: Text("OPEN"),
                                    onPressed: () => Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                DeviceScreen(device: d))),
                                  );
                                }
                                return Text(snapshot.data.toString());
                              },
                            ),
                          ))
                      .toList(),
                ),
              ),
              StreamBuilder<List<ScanResult>>(
                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map(
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            r.device.connect();
                            return SensorPage(device: r.device);
                          })),
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: StreamBuilder<bool>(
        stream: FlutterBlue.instance.isScanning,
        initialData: false,
        builder: (c, snapshot) {
          if (snapshot.data) {
            return FloatingActionButton(
              child: Icon(Icons.stop),
              onPressed: () => FlutterBlue.instance.stopScan(),
              backgroundColor: Colors.red,
            );
          } else {
            return FloatingActionButton(
                child: Icon(Icons.search),
                onPressed: () => FlutterBlue.instance
                    .startScan(timeout: Duration(seconds: 4)));
          }
        },
      ),
    );
  }
}

class DeviceScreen extends StatelessWidget {
  const DeviceScreen({Key key, this.device}) : super(key: key);
  final BluetoothDevice device;

  List<Widget> _buildServiceTiles(List<BluetoothService> services) {
    return services
        .map(
          (s) => ServiceTile(
            service: s,
            characteristicTiles: s.characteristics
                .map(
                  (c) => CharacteristicTile(
                    characteristic: c,
                    onReadPressed: () => c.read(),
                    onWritePressed: () => c.write([13, 24]),
                    onNotificationPressed: () =>
                        c.setNotifyValue(!c.isNotifying),
                    descriptorTiles: c.descriptors
                        .map(
                          (d) => DescriptorTile(
                            descriptor: d,
                            onReadPressed: () => d.read(),
                            onWritePressed: () => d.write([11, 12]),
                          ),
                        )
                        .toList(),
                  ),
                )
                .toList(),
          ),
        )
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(device.name),
        actions: <Widget>[
          StreamBuilder<BluetoothDeviceState>(
            stream: device.state,
            initialData: BluetoothDeviceState.connecting,
            builder: (c, snapshot) {
              VoidCallback onPressed;
              String text;
              switch (snapshot.data) {
                case BluetoothDeviceState.connected:
                  onPressed = () => device.disconnect();
                  text = "DISCONNECT";
                  break;
                case BluetoothDeviceState.disconnected:
                  onPressed = () => device.connect();
                  text = "CONNECT";
                  break;
                default:
                  onPressed = null;
                  text = snapshot.data.toString().substring(21).toUpperCase();
                  break;
              }
              return FlatButton(
                onPressed: onPressed,
                child: Text(
                  text,
                  style: Theme.of(context)
                      .primaryTextTheme
                      .button
                      .copyWith(color: Colors.white),
                ),
              );
            },
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            StreamBuilder<BluetoothDeviceState>(
              stream: device.state,
              initialData: BluetoothDeviceState.connecting,
              builder: (c, snapshot) => ListTile(
                leading: (snapshot.data == BluetoothDeviceState.connected)
                    ? Icon(Icons.bluetooth_connected)
                    : Icon(Icons.bluetooth_disabled),
                title: Text(
                    "Device is ${snapshot.data.toString().split('.')[1]}."),
                subtitle: Text("${device.id}"),
                trailing: StreamBuilder<bool>(
                  stream: device.isDiscoveringServices,
                  initialData: false,
                  builder: (c, snapshot) => IndexedStack(
                    index: snapshot.data ? 1 : 0,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(Icons.refresh),
                        onPressed: () => device.discoverServices(),
                      ),
                      IconButton(
                        icon: SizedBox(
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation(Colors.grey),
                          ),
                          width: 18.0,
                          height: 18.0,
                        ),
                        onPressed: null,
                      )
                    ],
                  ),
                ),
              ),
            ),
            StreamBuilder<int>(
              stream: device.mtu,
              initialData: 0,
              builder: (c, snapshot) => ListTile(
                title: Text("MTU Size"),
                subtitle: Text("${snapshot.data} bytes"),
                trailing: IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => device.requestMtu(223),
                ),
              ),
            ),
            StreamBuilder<List<BluetoothService>>(
              stream: device.services,
              initialData: [],
              builder: (c, snapshot) {
                return Column(
                  children: _buildServiceTiles(snapshot.data),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

My werte.dart file, where the values are received from the microcontroller:

```<code>import 'dart:async';
import 'dart:convert' show utf8;

import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:audioplayers/audioplayers.dart';
//import 'package:android_alarm_manager/android_alarm_manager.dart';

class SensorPage extends StatefulWidget {
  const SensorPage({Key key, this.device}) : super(key: key);
  final BluetoothDevice device;

  @override
  _SensorPageState createState() => _SensorPageState();
}

class _SensorPageState extends State<SensorPage> {
  final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
  final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
  bool isReady;
  var extrem = 0;
  var val1 = "";
  var pot1 = 0;
  var val2 = "";
  var pot2 = 0;
  var x = 0;

  Stream<List<int>> stream;

  AudioPlayer advancedPlayer;
  AudioCache audioCache;

  //var state;

  /*void printHello() {
    initState();
    /*final DateTime now = DateTime.now();
    print("[$now] Hello, world! function='$printHello'");*/
  }*/

  @override
  void initState() {
    super.initState();
    isReady = false;
    initPlayer();
    connectToDevice();
  }

  bool _isVisible = true;

  void showToast() {
    setState(() {
      _isVisible = !_isVisible;
    });
  }

  /*void alarmmanager() async {
    await AndroidAlarmManager.initialize();
    await AndroidAlarmManager.oneShot(
        const Duration(seconds: 1), 0, printHello);
  }*/

  void initPlayer() {
    advancedPlayer = new AudioPlayer();
    audioCache = new AudioCache(fixedPlayer: advancedPlayer);
  }

  String localFilePath;

  connectToDevice() async {
    if (widget.device == null) {
      _Pop();
      return;
    }

    new Timer(
      const Duration(seconds: 15),
      () {
        if (!isReady) {
          disconnectFromDevice();
          _Pop();
        }
      },
    );

    await widget.device.connect();
    discoverServices();
  }

  disconnectFromDevice() {
    if (widget.device == null) {
      _Pop();
      return;
    }

    widget.device.disconnect();
  }

  discoverServices() async {
    if (widget.device == null) {
      _Pop();
      return;
    }

    List<BluetoothService> services = await widget.device.discoverServices();
    services.forEach((service) {
      if (service.uuid.toString() == SERVICE_UUID) {
        service.characteristics.forEach((characteristic) {
          if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
            characteristic.setNotifyValue(!characteristic.isNotifying);
            stream = characteristic.value;

            setState(() {
              isReady = true;
            });
          }
        });
      }
    });

    if (!isReady) {
      _Pop();
    }
  }

  Future<bool> _onWillPop() {
    return showDialog(
        context: context,
        builder: (context) =>
            new AlertDialog(
              title: Text(
                "ARE YOU SURE?",
                style: TextStyle(fontSize: 18, fontFamily: "Montserrat"),
              ),
              content: Text(
                "DO YOU WANT TO DISCONNECT DEVICE AND GO BACK?",
                style: TextStyle(fontSize: 18, fontFamily: "Montserrat"),
              ),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    "NO",
                    style: TextStyle(fontSize: 14, fontFamily: "Montserrat"),
                  ),
                ),
                new FlatButton(
                  onPressed: () {
                    disconnectFromDevice();
                    Navigator.of(context).pop(true);
                  },
                  child: new Text(
                    "YES",
                    style: TextStyle(fontSize: 14, fontFamily: "Montserrat"),
                  ),
                ),
              ],
            ) ??
            false);
  }

  _Pop() {
    Navigator.of(context).pop(true);
  }

  String _dataParser(List<int> dataFromDevice) {
    return utf8.decode(dataFromDevice);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red[800],
          title: Text(
            "T(RAIN)-SHIRT",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
          ),
        ),
        body: Container(
          child: !isReady
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : Container(
                  child: StreamBuilder<List<int>>(
                    stream: stream,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<int>> snapshot) {
                      if (snapshot.hasError)
                        return Text("Error: ${snapshot.error}");

                      if (snapshot.connectionState == ConnectionState.active) {
                        if (x > 0) {
                          var currentValue = _dataParser(snapshot.data);
                          val1 = currentValue.split(',')[0];
                          pot1 = int.parse(val1);
                          val2 = currentValue.split(',')[1];
                          pot2 = int.parse(val2);
                        }

                        if (pot1 >= 1500 && pot1 < 2500) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(0.3);
                          extrem++;
                        } else if (pot1 >= 2500 && pot1 < 3500) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(0.6);
                          extrem++;
                        } else if (pot1 >= 3500 && pot1 <= 4095) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(1.0);
                          extrem++;
                        } else {
                          advancedPlayer.stop();
                        }

                        //alarmmanager();

                        return Center(
                          child: Visibility(
                            visible: _isVisible,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text(
                                  "$extrem",
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                RaisedButton(
                                  child: Text(
                                    "START",
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: "Montserrat"),
                                  ),
                                  onPressed: () {
                                    showToast();
                                    x++;
                                    extrem = 0;
                                  },
                                  color: Colors.red[800],
                                ),
                              ],
                            ),
                            replacement: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text(
                                  "$pot1",
                                  style: TextStyle(
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                Text(
                                  "$pot2",
                                  style: TextStyle(
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                RaisedButton(
                                  child: Text(
                                    "STOP",
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: "Montserrat"),
                                  ),
                                  onPressed: () {
                                    showToast();
                                    x = 0;
                                    pot1 = 0;
                                    pot2 = 0;
                                  },
                                  color: Colors.red[800],
                                ),
                              ],
                            ),
                          ),
                        );
                      } else {
                        return Text("CHECK THE STREAM");
                      }
                    },
                  ),
                ),
        ),
        backgroundColor: Colors.grey[300],
      ),
    );
  }
}
</code>```

If I'm in "background-mode", I want to still receive data from the ESP32 and than play the sound, if the condition is true.
Maybe someone has a simple solution, on how to execute Dart Code in the background.

Thank you!

答: If you're planning to run tasks in the background, you might want to consider using Isolate. Here's a well written guide on creating background tasks to help you get started. You can also check this post for a simple run through of Isolates.</p>

Body:
right now I'm working on a project, where I'm sending data from a microcontroller (ESP32) to my Flutter App via BLE. When one value of the data is greater than a defined limit, a sound is played, and then stopped, when its lower than the limit.
Now the problem: If the App is in "background-mode", the Dart Code won't be executed.
If tried to solve the problem, with the android-alarm-manager plugin or the WidgetBindingObserver, but couldn't find a proper solution.

My main.dart file:

// Copyright 2017, Paul DeMarco.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_app_2/werte.dart';
import 'package:flutter_blue_app_2/widgets.dart';
import 'package:flutter_blue/flutter_blue.dart';

void main() {
  runApp(FlutterBlueApp());
}

class FlutterBlueApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      color: Colors.lightBlue,
      home: StreamBuilder<BluetoothState>(
          stream: FlutterBlue.instance.state,
          initialData: BluetoothState.unknown,
          builder: (c, snapshot) {
            final state = snapshot.data;
            if (state == BluetoothState.on) {
              return FindDevicesScreen();
            }
            return BluetoothOffScreen(state: state);
          }),
    );
  }
}

class BluetoothOffScreen extends StatelessWidget {
  const BluetoothOffScreen({Key key, this.state}) : super(key: key);
  final BluetoothState state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Icon(
              Icons.bluetooth_disabled,
              size: 200.0,
              color: Colors.white54,
            ),
            Text(
              "BLUETOOTH ADAPTER IS ${state.toString().substring(15)}.",
              style: Theme.of(context)
                  .primaryTextTheme
                  .subhead
                  .copyWith(color: Colors.white),
            ),
          ],
        ),
      ),
    );
  }
}

class FindDevicesScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FIND DEVICES ..."),
      ),
      body: RefreshIndicator(
        onRefresh: () =>
            FlutterBlue.instance.startScan(timeout: Duration(seconds: 4)),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              StreamBuilder<List<BluetoothDevice>>(
                stream: Stream.periodic(Duration(seconds: 2))
                    .asyncMap((_) => FlutterBlue.instance.connectedDevices),
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map((d) => ListTile(
                            title: Text(d.name),
                            subtitle: Text(d.id.toString()),
                            trailing: StreamBuilder<BluetoothDeviceState>(
                              stream: d.state,
                              initialData: BluetoothDeviceState.disconnected,
                              builder: (c, snapshot) {
                                if (snapshot.data ==
                                    BluetoothDeviceState.connected) {
                                  return RaisedButton(
                                    child: Text("OPEN"),
                                    onPressed: () => Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                DeviceScreen(device: d))),
                                  );
                                }
                                return Text(snapshot.data.toString());
                              },
                            ),
                          ))
                      .toList(),
                ),
              ),
              StreamBuilder<List<ScanResult>>(
                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data
                      .map(
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            r.device.connect();
                            return SensorPage(device: r.device);
                          })),
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: StreamBuilder<bool>(
        stream: FlutterBlue.instance.isScanning,
        initialData: false,
        builder: (c, snapshot) {
          if (snapshot.data) {
            return FloatingActionButton(
              child: Icon(Icons.stop),
              onPressed: () => FlutterBlue.instance.stopScan(),
              backgroundColor: Colors.red,
            );
          } else {
            return FloatingActionButton(
                child: Icon(Icons.search),
                onPressed: () => FlutterBlue.instance
                    .startScan(timeout: Duration(seconds: 4)));
          }
        },
      ),
    );
  }
}

class DeviceScreen extends StatelessWidget {
  const DeviceScreen({Key key, this.device}) : super(key: key);
  final BluetoothDevice device;

  List<Widget> _buildServiceTiles(List<BluetoothService> services) {
    return services
        .map(
          (s) => ServiceTile(
            service: s,
            characteristicTiles: s.characteristics
                .map(
                  (c) => CharacteristicTile(
                    characteristic: c,
                    onReadPressed: () => c.read(),
                    onWritePressed: () => c.write([13, 24]),
                    onNotificationPressed: () =>
                        c.setNotifyValue(!c.isNotifying),
                    descriptorTiles: c.descriptors
                        .map(
                          (d) => DescriptorTile(
                            descriptor: d,
                            onReadPressed: () => d.read(),
                            onWritePressed: () => d.write([11, 12]),
                          ),
                        )
                        .toList(),
                  ),
                )
                .toList(),
          ),
        )
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(device.name),
        actions: <Widget>[
          StreamBuilder<BluetoothDeviceState>(
            stream: device.state,
            initialData: BluetoothDeviceState.connecting,
            builder: (c, snapshot) {
              VoidCallback onPressed;
              String text;
              switch (snapshot.data) {
                case BluetoothDeviceState.connected:
                  onPressed = () => device.disconnect();
                  text = "DISCONNECT";
                  break;
                case BluetoothDeviceState.disconnected:
                  onPressed = () => device.connect();
                  text = "CONNECT";
                  break;
                default:
                  onPressed = null;
                  text = snapshot.data.toString().substring(21).toUpperCase();
                  break;
              }
              return FlatButton(
                onPressed: onPressed,
                child: Text(
                  text,
                  style: Theme.of(context)
                      .primaryTextTheme
                      .button
                      .copyWith(color: Colors.white),
                ),
              );
            },
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            StreamBuilder<BluetoothDeviceState>(
              stream: device.state,
              initialData: BluetoothDeviceState.connecting,
              builder: (c, snapshot) => ListTile(
                leading: (snapshot.data == BluetoothDeviceState.connected)
                    ? Icon(Icons.bluetooth_connected)
                    : Icon(Icons.bluetooth_disabled),
                title: Text(
                    "Device is ${snapshot.data.toString().split('.')[1]}."),
                subtitle: Text("${device.id}"),
                trailing: StreamBuilder<bool>(
                  stream: device.isDiscoveringServices,
                  initialData: false,
                  builder: (c, snapshot) => IndexedStack(
                    index: snapshot.data ? 1 : 0,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(Icons.refresh),
                        onPressed: () => device.discoverServices(),
                      ),
                      IconButton(
                        icon: SizedBox(
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation(Colors.grey),
                          ),
                          width: 18.0,
                          height: 18.0,
                        ),
                        onPressed: null,
                      )
                    ],
                  ),
                ),
              ),
            ),
            StreamBuilder<int>(
              stream: device.mtu,
              initialData: 0,
              builder: (c, snapshot) => ListTile(
                title: Text("MTU Size"),
                subtitle: Text("${snapshot.data} bytes"),
                trailing: IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => device.requestMtu(223),
                ),
              ),
            ),
            StreamBuilder<List<BluetoothService>>(
              stream: device.services,
              initialData: [],
              builder: (c, snapshot) {
                return Column(
                  children: _buildServiceTiles(snapshot.data),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

My werte.dart file, where the values are received from the microcontroller:

import 'dart:async';
import 'dart:convert' show utf8;

import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:audioplayers/audioplayers.dart';
//import 'package:android_alarm_manager/android_alarm_manager.dart';

class SensorPage extends StatefulWidget {
  const SensorPage({Key key, this.device}) : super(key: key);
  final BluetoothDevice device;

  @override
  _SensorPageState createState() => _SensorPageState();
}

class _SensorPageState extends State<SensorPage> {
  final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
  final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
  bool isReady;
  var extrem = 0;
  var val1 = "";
  var pot1 = 0;
  var val2 = "";
  var pot2 = 0;
  var x = 0;

  Stream<List<int>> stream;

  AudioPlayer advancedPlayer;
  AudioCache audioCache;

  //var state;

  /*void printHello() {
    initState();
    /*final DateTime now = DateTime.now();
    print("[$now] Hello, world! function='$printHello'");*/
  }*/

  @override
  void initState() {
    super.initState();
    isReady = false;
    initPlayer();
    connectToDevice();
  }

  bool _isVisible = true;

  void showToast() {
    setState(() {
      _isVisible = !_isVisible;
    });
  }

  /*void alarmmanager() async {
    await AndroidAlarmManager.initialize();
    await AndroidAlarmManager.oneShot(
        const Duration(seconds: 1), 0, printHello);
  }*/

  void initPlayer() {
    advancedPlayer = new AudioPlayer();
    audioCache = new AudioCache(fixedPlayer: advancedPlayer);
  }

  String localFilePath;

  connectToDevice() async {
    if (widget.device == null) {
      _Pop();
      return;
    }

    new Timer(
      const Duration(seconds: 15),
      () {
        if (!isReady) {
          disconnectFromDevice();
          _Pop();
        }
      },
    );

    await widget.device.connect();
    discoverServices();
  }

  disconnectFromDevice() {
    if (widget.device == null) {
      _Pop();
      return;
    }

    widget.device.disconnect();
  }

  discoverServices() async {
    if (widget.device == null) {
      _Pop();
      return;
    }

    List<BluetoothService> services = await widget.device.discoverServices();
    services.forEach((service) {
      if (service.uuid.toString() == SERVICE_UUID) {
        service.characteristics.forEach((characteristic) {
          if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
            characteristic.setNotifyValue(!characteristic.isNotifying);
            stream = characteristic.value;

            setState(() {
              isReady = true;
            });
          }
        });
      }
    });

    if (!isReady) {
      _Pop();
    }
  }

  Future<bool> _onWillPop() {
    return showDialog(
        context: context,
        builder: (context) =>
            new AlertDialog(
              title: Text(
                "ARE YOU SURE?",
                style: TextStyle(fontSize: 18, fontFamily: "Montserrat"),
              ),
              content: Text(
                "DO YOU WANT TO DISCONNECT DEVICE AND GO BACK?",
                style: TextStyle(fontSize: 18, fontFamily: "Montserrat"),
              ),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    "NO",
                    style: TextStyle(fontSize: 14, fontFamily: "Montserrat"),
                  ),
                ),
                new FlatButton(
                  onPressed: () {
                    disconnectFromDevice();
                    Navigator.of(context).pop(true);
                  },
                  child: new Text(
                    "YES",
                    style: TextStyle(fontSize: 14, fontFamily: "Montserrat"),
                  ),
                ),
              ],
            ) ??
            false);
  }

  _Pop() {
    Navigator.of(context).pop(true);
  }

  String _dataParser(List<int> dataFromDevice) {
    return utf8.decode(dataFromDevice);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red[800],
          title: Text(
            "T(RAIN)-SHIRT",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
          ),
        ),
        body: Container(
          child: !isReady
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : Container(
                  child: StreamBuilder<List<int>>(
                    stream: stream,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<int>> snapshot) {
                      if (snapshot.hasError)
                        return Text("Error: ${snapshot.error}");

                      if (snapshot.connectionState == ConnectionState.active) {
                        if (x > 0) {
                          var currentValue = _dataParser(snapshot.data);
                          val1 = currentValue.split(',')[0];
                          pot1 = int.parse(val1);
                          val2 = currentValue.split(',')[1];
                          pot2 = int.parse(val2);
                        }

                        if (pot1 >= 1500 && pot1 < 2500) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(0.3);
                          extrem++;
                        } else if (pot1 >= 2500 && pot1 < 3500) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(0.6);
                          extrem++;
                        } else if (pot1 >= 3500 && pot1 <= 4095) {
                          audioCache.play("audio.mp4");
                          advancedPlayer.setVolume(1.0);
                          extrem++;
                        } else {
                          advancedPlayer.stop();
                        }

                        //alarmmanager();

                        return Center(
                          child: Visibility(
                            visible: _isVisible,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text(
                                  "$extrem",
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                RaisedButton(
                                  child: Text(
                                    "START",
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: "Montserrat"),
                                  ),
                                  onPressed: () {
                                    showToast();
                                    x++;
                                    extrem = 0;
                                  },
                                  color: Colors.red[800],
                                ),
                              ],
                            ),
                            replacement: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text(
                                  "$pot1",
                                  style: TextStyle(
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                Text(
                                  "$pot2",
                                  style: TextStyle(
                                      fontSize: 30,
                                      fontWeight: FontWeight.bold,
                                      fontFamily: "Montserrat"),
                                ),
                                RaisedButton(
                                  child: Text(
                                    "STOP",
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold,
                                        fontFamily: "Montserrat"),
                                  ),
                                  onPressed: () {
                                    showToast();
                                    x = 0;
                                    pot1 = 0;
                                    pot2 = 0;
                                  },
                                  color: Colors.red[800],
                                ),
                              ],
                            ),
                          ),
                        );
                      } else {
                        return Text("CHECK THE STREAM");
                      }
                    },
                  ),
                ),
        ),
        backgroundColor: Colors.grey[300],
      ),
    );
  }
}

If I'm in "background-mode", I want to still receive data from the ESP32 and than play the sound, if the condition is true.
Maybe someone has a simple solution, on how to execute Dart Code in the background.

Thank you!


来源: stackexchange

问:
Flutter How to create box container with arrow on top?
Hi how do i create box container with arrow on top without using any pub packages.

Like below.

答:
You can customize ShapeBorder similar to this post. Then instead of using rect.bottomCenter for Path(), change it to rect.TopCenter to place the drawn Rect at the top.

```<code>Path()dart
  ..addRRect(RRect.fromRectAndRadius(rect, Radius.circular(rect.height / 2)))
  ..moveTo(rect.topCenter.dx - 10, rect.topCenter.dy)
  ..relativeLineTo(10, 20)
  ..relativeLineTo(20, -20)
  ..close();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can customize ShapeBorder similar to this post. Then instead of using rect.bottomCenter for Path(), change it to rect.TopCenter to place the drawn Rect at the top.

Path()dart
  ..addRRect(RRect.fromRectAndRadius(rect, Radius.circular(rect.height / 2)))
  ..moveTo(rect.topCenter.dx - 10, rect.topCenter.dy)
  ..relativeLineTo(10, 20)
  ..relativeLineTo(20, -20)
  ..close();


问:
flutter crashing Attempt to invoke virtual method
I'm facing weird issue that make app crashing in production mode and it's happened once time and don't happened if I try same action I have did , so when try add item in firebase it's crashing and if return try same item in same condition maybe didn't crashed but I have cashed these issues

the first issue

```<code>/AndroidRuntime( 9758): java.lang.NullPointerException: Attempt to invoke virtual method 'void io.flutter.plugin.common.MethodChannel.invokeMethod(java.lang.String, java.lang.Object)' on a null object reference
E/AndroidRuntime( 9758):    at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$EventObserver.onEvent(CloudFirestorePlugin.java:451)
E/AndroidRuntime( 9758):    at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$EventObserver.onEvent(CloudFirestorePlugin.java:433)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(com.google.firebase:firebase-firestore@@21.3.0:1025)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.Query$$Lambda$3.onEvent(Unknown Source:6)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(com.google.firebase:firebase-firestore@@21.3.0:42)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
E/AndroidRuntime( 9758):    at android.os.Handler.handleCallback(Handler.java:873)
E/AndroidRuntime( 9758):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 9758):    at com.google.android.gms.internal.tasks.zzb.dispatchMessage(com.google.android.gms:play-services-tasks@@17.0.2:6)
E/AndroidRuntime( 9758):    at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime( 9758):    at android.app.ActivityThread.main(ActivityThread.java:7156)
E/AndroidRuntime( 9758):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 9758):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/AndroidRuntime( 9758):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
I/System.out( 9758): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out( 9758): (HTTPLog)-Static: isSBSettingEnabled false
D/NetworkManagementSocketTagger( 9758): tagSocket(93) with statsTag=0xffffffff, statsUid=-1
D/NetworkManagementSocketTagger( 9758): tagSocket(65) with statsTag=0xffffffff, statsUid=-1
</code>```

the second issue

```<code>Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'void j.b.a.a.n.a(java.lang.String, java.lang.Object)' on a null object reference
io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$DocumentObserver.a (CloudFirestorePlugin.java:106)
io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$DocumentObserver.a (CloudFirestorePlugin.java:2)
com.google.firebase.firestore.DocumentReference.a (DocumentReference.java:87)
com.google.firebase.firestore.DocumentReference$$Lambda$3.a (DocumentReference.java:6)
com.google.firebase.firestore.core.AsyncEventListener.a (AsyncEventListener.java:6)
com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run (AsyncEventListener.java:6)
android.os.Handler.handleCallback (Handler.java:873)
android.os.Handler.dispatchMessage (Handler.java:99)
com.google.android.gms.internal.tasks.zzb.dispatchMessage (zzb.java)
android.os.Looper.loop (Looper.java:214)
android.app.ActivityThread.main (ActivityThread.java:7156)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:975)
</code>```

another issue

```<code>E/flutter (24582): [ERROR:flutter/shell/platform/android/platform_view_android_jni.cc(39)] java.lang.AssertionError: java.lang.NoSuchFieldException: DrawableResource
E/flutter (24582):      at c.c.e.y.n.n$k0.<init>(Unknown Source:87)
E/flutter (24582):      at c.c.e.y.n.n$w.a(Unknown Source:29)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:74)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:42)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:123)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:22)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:74)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:4)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:8)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:5)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:13)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.b(Unknown Source:4)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.f(Unknown Source:19)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.onMethodCall(Unknown Source:169)
E/flutter (24582):      at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(Unknown Source:17)
E/flutter (24582):      at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(Unknown Source:57)
E/flutter (24582):      at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(Unknown Source:4)
E/flutter (24582):      at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (24582):      at android.os.MessageQueue.next(MessageQueue.java:326)
E/flutter (24582):      at android.os.Looper.loop(Looper.java:181)
E/flutter (24582):      at android.app.ActivityThread.main(ActivityThread.java:7156)
E/flutter (24582):      at java.lang.reflect.Method.invoke(Native Method)
E/flutter (24582):      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/flutter (24582):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
E/flutter (24582): Caused by: java.lang.NoSuchFieldException: DrawableResource
E/flutter (24582):      at java.lang.Class.getField(Class.java:1601)
E/flutter (24582):      at c.c.e.y.n.n$k0.<init>(Unknown Source:34)
E/flutter (24582):      ... 23 more
E/flutter (24582):
F/flutter (24582): [FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(76)] Check failed: CheckException(env).
</code>```

答: This issue doesn't seem to happen on cloud_firestore: ^3.1.7. Try updating the cloud_firestore version that you're using. If that doesn't work, see if proguard is enabled on your Android build. Updating android.enableR8=false the Android build's gradle.properties also works to some.

Body:
I'm facing weird issue that make app crashing in production mode and it's happened once time and don't happened if I try same action I have did , so when try add item in firebase it's crashing and if return try same item in same condition maybe didn't crashed but I have cashed these issues

the first issue

/AndroidRuntime( 9758): java.lang.NullPointerException: Attempt to invoke virtual method 'void io.flutter.plugin.common.MethodChannel.invokeMethod(java.lang.String, java.lang.Object)' on a null object reference
E/AndroidRuntime( 9758):    at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$EventObserver.onEvent(CloudFirestorePlugin.java:451)
E/AndroidRuntime( 9758):    at io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$EventObserver.onEvent(CloudFirestorePlugin.java:433)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(com.google.firebase:firebase-firestore@@21.3.0:1025)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.Query$$Lambda$3.onEvent(Unknown Source:6)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(com.google.firebase:firebase-firestore@@21.3.0:42)
E/AndroidRuntime( 9758):    at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
E/AndroidRuntime( 9758):    at android.os.Handler.handleCallback(Handler.java:873)
E/AndroidRuntime( 9758):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 9758):    at com.google.android.gms.internal.tasks.zzb.dispatchMessage(com.google.android.gms:play-services-tasks@@17.0.2:6)
E/AndroidRuntime( 9758):    at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime( 9758):    at android.app.ActivityThread.main(ActivityThread.java:7156)
E/AndroidRuntime( 9758):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 9758):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/AndroidRuntime( 9758):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
I/System.out( 9758): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out( 9758): (HTTPLog)-Static: isSBSettingEnabled false
D/NetworkManagementSocketTagger( 9758): tagSocket(93) with statsTag=0xffffffff, statsUid=-1
D/NetworkManagementSocketTagger( 9758): tagSocket(65) with statsTag=0xffffffff, statsUid=-1

the second issue

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'void j.b.a.a.n.a(java.lang.String, java.lang.Object)' on a null object reference
io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$DocumentObserver.a (CloudFirestorePlugin.java:106)
io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$DocumentObserver.a (CloudFirestorePlugin.java:2)
com.google.firebase.firestore.DocumentReference.a (DocumentReference.java:87)
com.google.firebase.firestore.DocumentReference$$Lambda$3.a (DocumentReference.java:6)
com.google.firebase.firestore.core.AsyncEventListener.a (AsyncEventListener.java:6)
com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run (AsyncEventListener.java:6)
android.os.Handler.handleCallback (Handler.java:873)
android.os.Handler.dispatchMessage (Handler.java:99)
com.google.android.gms.internal.tasks.zzb.dispatchMessage (zzb.java)
android.os.Looper.loop (Looper.java:214)
android.app.ActivityThread.main (ActivityThread.java:7156)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:975)

another issue

E/flutter (24582): [ERROR:flutter/shell/platform/android/platform_view_android_jni.cc(39)] java.lang.AssertionError: java.lang.NoSuchFieldException: DrawableResource
E/flutter (24582):      at c.c.e.y.n.n$k0.<init>(Unknown Source:87)
E/flutter (24582):      at c.c.e.y.n.n$w.a(Unknown Source:29)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:74)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:42)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:123)
E/flutter (24582):      at c.c.e.y.n.i.a(Unknown Source:22)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:74)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:4)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:8)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:5)
E/flutter (24582):      at c.c.e.f.a(Unknown Source:13)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.b(Unknown Source:4)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.f(Unknown Source:19)
E/flutter (24582):      at com.dexterous.flutterlocalnotifications.b.onMethodCall(Unknown Source:169)
E/flutter (24582):      at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(Unknown Source:17)
E/flutter (24582):      at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(Unknown Source:57)
E/flutter (24582):      at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(Unknown Source:4)
E/flutter (24582):      at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (24582):      at android.os.MessageQueue.next(MessageQueue.java:326)
E/flutter (24582):      at android.os.Looper.loop(Looper.java:181)
E/flutter (24582):      at android.app.ActivityThread.main(ActivityThread.java:7156)
E/flutter (24582):      at java.lang.reflect.Method.invoke(Native Method)
E/flutter (24582):      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/flutter (24582):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
E/flutter (24582): Caused by: java.lang.NoSuchFieldException: DrawableResource
E/flutter (24582):      at java.lang.Class.getField(Class.java:1601)
E/flutter (24582):      at c.c.e.y.n.n$k0.<init>(Unknown Source:34)
E/flutter (24582):      ... 23 more
E/flutter (24582):
F/flutter (24582): [FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(76)] Check failed: CheckException(env).


问:
Terraform API Gateway v2 Authorizer - Automatically grant API Gateway permission to invoke your Lambda function
In the AWS Console, one has the ability to create an API Gateway Authorizer with a true/false value for "Automatically grant API Gateway

However, I don't see this flag exposed via the AWS provider in Terraform for the aws_apigatewayv2_authorizer resource.

Is there a way to set this via Terraform?

答:
In terraform you need to manually create your IAM statements to make this work. The easiest way is with a resource policy associated with your lambda:</p>
```<code>resource "aws_lambda_permission" "my_authorizer_lambda_permission" {
    statement_id  = "AllowAPIGatewayInvoke"
    action        = "lambda:InvokeFunction"
    function_name = aws_lambda_function.onconnect.function_name
    principal     = "apigateway.amazonaws.com"

    source_arn    = "${aws_apigatewayv2_api.my_api.execution_arn}/authorizers/${aws_apigatewayv2_authorizer.my_authorizer.id}"
}
</code>```

Body:
In terraform you need to manually create your IAM statements to make this work. The easiest way is with a resource policy associated with your lambda:

resource "aws_lambda_permission" "my_authorizer_lambda_permission" {
    statement_id  = "AllowAPIGatewayInvoke"
    action        = "lambda:InvokeFunction"
    function_name = aws_lambda_function.onconnect.function_name
    principal     = "apigateway.amazonaws.com"

    source_arn    = "${aws_apigatewayv2_api.my_api.execution_arn}/authorizers/${aws_apigatewayv2_authorizer.my_authorizer.id}"
}


问:
How to draw a picture on a TPanel
How can i draw a picture on a TPanel? I also want to determine X,Y to define exact position on the Panel.

答:
Here is a simple code </p>

```<code>var
  eu:TImage;
begin
  eu:=TImage.Create(Panel1);
  eu.Parent:=Panel1;
  eu.Top:=30; // You can adjust the position by using these coordinates
  eu.Left:=50;
  eu.Picture.LoadFromFile('D:\usb.ico'); // Load any supported image
  eu.Visible:=True;
end;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to draw a picture on a TPanel

Body:
Here is a simple code

var
  eu:TImage;
begin
  eu:=TImage.Create(Panel1);
  eu.Parent:=Panel1;
  eu.Top:=30; // You can adjust the position by using these coordinates
  eu.Left:=50;
  eu.Picture.LoadFromFile('D:\usb.ico'); // Load any supported image
  eu.Visible:=True;
end;


问:
Flutter check if Asset image exists
Is it possible to conditionally load an asset image, only if it exists? Therefore you could load a default image if it does not exist in the Assets bundle.</p>

答:
One way you can check if the asset image exists is by trying to display it. If it throws an Exception, display a different widget instead.

```<code>Future<Widget> getAssetImage(String path) async {
  try {
    await rootBundle.load(path);
    return Image.asset(path);
  } catch (_) {
    return SizedBox(); // Return this widget
  }
}
</code>```

Otherwise, you can check the AssetManifest.json and cross-check the asset to be used with the list before trying to access it.

Title: Flutter check if Asset image exists

Body:
One way you can check if the asset image exists is by trying to display it. If it throws an Exception, display a different widget instead.

Future<Widget> getAssetImage(String path) async {
  try {
    await rootBundle.load(path);
    return Image.asset(path);
  } catch (_) {
    return SizedBox(); // Return this widget
  }
}

Otherwise, you can check the AssetManifest.json and cross-check the asset to be used with the list before trying to access it.


问:
How to create facebook like comment structure in flutter?
I am trying to construct comment section in a project I am working on. And I want it the way facebook have done it. I have taken care of almost everything right now but how can I populate a field right below the original comment and create another comment field which will be typed when pressed reply?

Please have a look at the code and help me with this.

```<code>    class MyHomePageState extends State<MyHomePage> {
  Widget postComment(String time, String postComment, String profileName,
      String profileImage, int likeCount) {
    return Padding(
      padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          CircleAvatar(maxRadius: 16, child: Image.asset(profileImage)),
          SizedBox(
            width: 16.0,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Hexcolor('#E9F1FE'),
                  borderRadius: BorderRadius.circular(6.0),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        profileName,
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      Text(
                        postComment,
                        style: TextStyle(fontSize: 16.0),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 12.0,
              ),
              Row(
                children: [
                  Text(time, style: TextStyle(fontWeight: FontWeight.w600)),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.1,
                  ),
                  Text('Like', style: TextStyle(fontWeight: FontWeight.w600)),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.1,
                  ),
                  InkWell(
                    onTap: () {},
                    child: Text(
                      'Reply',
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.24,
                  ),
                  InkWell(
                      onTap: () {
                        // _incrementCommentLikeCount();
                      },
                      child: Text('$likeCount')),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.02,
                  ),
                  SvgPicture.asset('assets/like.svg')
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(
      children: [
        ///Just calling the widget for sake of example
        postComment(
            '2h', 'This is a comment', 'Unknown Name', 'assets/img1.png', 10)
      ],
    ));
  }
}
</code>```

Here is the output:

答:
If you're looking for ways on how you can update a ListView, you can populate the ListView with a List of Objects i.e. List<Comment> _comments;.

As an example, you can create a Comment model

class Comment {
  String commentId;
  String userId;
  String comment;
  Timestamp timestamp;

  Comment(
      {required this.id,
        required this.sender,
        required this.comment,
        required this.timestamp});
...
```
<p>Then use the List to populate ListView.builder with data.</p>
<pre class="lang-dart prettyprint-override"><code>ListView.builder(
  itemCount: _comments.length,
  itemBuilder: (BuildContext context, int index) {
    // Return a Widget for the comments
    return Container(...);
  }
)
</code>```

You can then access Comment objects inside List<Comment> using the index provided by ListView.builder()

i.e. Text('${_comments[index].comment}')

To add new comments on the List, you can just add new Comment objects on the List.

_comments.add(Comment(
  commentId: generatedCommentId,
  userId: senderUserId,
  comment: senderMessage,
  timestamp: DateTime.now(),
));
```

Body:
I am trying to construct comment section in a project I am working on. And I want it the way facebook have done it. I have taken care of almost everything right now but how can I populate a field right below the original comment and create another comment field which will be typed when pressed reply?

Please have a look at the code and help me with this.

    class MyHomePageState extends State<MyHomePage> {
  Widget postComment(String time, String postComment, String profileName,
      String profileImage, int likeCount) {
    return Padding(
      padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          CircleAvatar(maxRadius: 16, child: Image.asset(profileImage)),
          SizedBox(
            width: 16.0,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Hexcolor('#E9F1FE'),
                  borderRadius: BorderRadius.circular(6.0),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        profileName,
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      Text(
                        postComment,
                        style: TextStyle(fontSize: 16.0),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 12.0,
              ),
              Row(
                children: [
                  Text(time, style: TextStyle(fontWeight: FontWeight.w600)),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.1,
                  ),
                  Text('Like', style: TextStyle(fontWeight: FontWeight.w600)),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.1,
                  ),
                  InkWell(
                    onTap: () {},
                    child: Text(
                      'Reply',
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.24,
                  ),
                  InkWell(
                      onTap: () {
                        // _incrementCommentLikeCount();
                      },
                      child: Text('$likeCount')),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.02,
                  ),
                  SvgPicture.asset('assets/like.svg')
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(
      children: [
        ///Just calling the widget for sake of example
        postComment(
            '2h', 'This is a comment', 'Unknown Name', 'assets/img1.png', 10)
      ],
    ));
  }
}

Here is the output:

Body:
If you're looking for ways on how you can update a ListView, you can populate the ListView with a List of Objects i.e. List<Comment> _comments;.

As an example, you can create a Comment model

class Comment {
  String commentId;
  String userId;
  String comment;
  Timestamp timestamp;

  Comment(
      {required this.id,
        required this.sender,
        required this.comment,
        required this.timestamp});
...

Then use the List to populate ListView.builder with data.

ListView.builder(
  itemCount: _comments.length,
  itemBuilder: (BuildContext context, int index) {
    // Return a Widget for the comments
    return Container(...);
  }
)

You can then access Comment objects inside List<Comment> using the index provided by ListView.builder()

i.e. Text('${_comments[index].comment}')

To add new comments on the List, you can just add new Comment objects on the List.

_comments.add(Comment(
  commentId: generatedCommentId,
  userId: senderUserId,
  comment: senderMessage,
  timestamp: DateTime.now(),
));


问:
Creating a React project in Visual Studio 2022 is not working, error on installing react react-dom react-scripts with cra-template
here is an image after a failed attempt at creating the react project on visual studio

I saved the log data, but how to upload it?

update : I reset my firewall and reinstalled nodejs and nothing change, it just either gets stuck or there is an error

答: It's most likely your internet connection blocking the connection for some reason. Trying another internet connection will eliminate that as a possibility.</p>


问:
Can't launch Spyder - 'Invalid file descriptor to ICU data received'
I can't run Spyder from windows shortcut. It doesn't open at all. After that I tried running it from Anaconda navigator which shows the following errors. I have uninstalled the Spyder and reinstalled it also. It happened after tried installing Opencv in Anaconda.</p>

```<code>[1205/235251.482:ERROR:icu_util.cc(178)] Invalid file descriptor to ICU data received.
[1205/235251.483:FATAL:icu_util.cc(297)] Check failed: result.
Backtrace:
GetHandleVerifier [0x00007FFA2A88D261+125633]
QWebEngineUrlSchemeHandler::qt_static_metacall [0x00007FFA2A822E63+5555]
GetHandleVerifier [0x00007FFA2AB7A3B5+3193877]
QtWebEngineCore::AuthenticationDialogController::qt_static_metacall [0x00007FFA2A8026F5+7629589]
QtWebEngineCore::WebContentsAdapter::webContents [0x00007FFA2A0A8351+20433]
QtWebEngineCore::WebContentsAdapter::webContents [0x00007FFA2A0A89BE+22078]
QtWebEngineCore::WebContentsAdapter::WebContentsAdapter [0x00007FFA2A09C038+56]
QWebEngineHistoryItem::url [0x00007FFA55253547+423]
QWebEnginePage::QWebEnginePage [0x00007FFA55253893+147]
QWebEnginePage::QWebEnginePage [0x00007FFA552537DD+45]
(No symbol) [0x00007FFA5C9483C4]
(No symbol) [0x00007FFA756313BF]
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\python\pythonrun.c:432)
PyRun_AnyFileExFlags [0x00007FFA537B513B+99] (c:\ci\python_1572550317365\work\python\pythonrun.c:85)
pymain_run_file [0x00007FFA5370137B+191] (c:\ci\python_1572550317365\work\modules\main.c:433)
pymain_run_filename [0x00007FFA53701423+111] (c:\ci\python_1572550317365\work\modules\main.c:1613)
pymain_run_python [0x00007FFA53670A24+390720] (c:\ci\python_1572550317365\work\modules\main.c:2873)
pymain_main [0x00007FFA536113A5+41] (c:\ci\python_1572550317365\work\modules\main.c:3415)
Py_Main [0x00007FFA53611052+82] (c:\ci\python_1572550317365\work\modules\main.c:3437)
</code>```

答: Actually, instead of copying the files to the Python root directory you should check the qt.conf file in the Python root directory whether it links to the correct subdirectories (cf. the answer here). If you get the error messages they are most likely wrong.</p>

Body:
I can't run Spyder from windows shortcut. It doesn't open at all. After that I tried running it from Anaconda navigator which shows the following errors. I have uninstalled the Spyder and reinstalled it also. It happened after tried installing Opencv in Anaconda.

[1205/235251.482:ERROR:icu_util.cc(178)] Invalid file descriptor to ICU data received.
[1205/235251.483:FATAL:icu_util.cc(297)] Check failed: result.
Backtrace:
GetHandleVerifier [0x00007FFA2A88D261+125633]
QWebEngineUrlSchemeHandler::qt_static_metacall [0x00007FFA2A822E63+5555]
GetHandleVerifier [0x00007FFA2AB7A3B5+3193877]
QtWebEngineCore::AuthenticationDialogController::qt_static_metacall [0x00007FFA2A8026F5+7629589]
QtWebEngineCore::WebContentsAdapter::webContents [0x00007FFA2A0A8351+20433]
QtWebEngineCore::WebContentsAdapter::webContents [0x00007FFA2A0A89BE+22078]
QtWebEngineCore::WebContentsAdapter::WebContentsAdapter [0x00007FFA2A09C038+56]
QWebEngineHistoryItem::url [0x00007FFA55253547+423]
QWebEnginePage::QWebEnginePage [0x00007FFA55253893+147]
QWebEnginePage::QWebEnginePage [0x00007FFA552537DD+45]
(No symbol) [0x00007FFA5C9483C4]
(No symbol) [0x00007FFA756313BF]
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\objects\call.c:199)
call_function [0x00007FFA53657709+1017] (c:\ci\python_1572550317365\work\python\ceval.c:4619)
_PyEval_EvalFrameDefault [0x00007FFA53657CEF+1199] (c:\ci\python_1572550317365\work\python\ceval.c:3125)
_PyFunction_FastCallDict [0x00007FFA53640C9D+221] (c:\ci\python_1572550317365\work\objects\call.c:322)
slot_tp_init [0x00007FFA5363EDF3+315] (c:\ci\python_1572550317365\work\objects\typeobject.c:6636)
type_call [0x00007FFA5364F8A7+167] (c:\ci\python_1572550317365\work\objects\typeobject.c:972)
_PyObject_FastCallKeywords [0x00007FFA5364F63A+378] (c:\ci\python_1572550317365\work\python\pythonrun.c:432)
PyRun_AnyFileExFlags [0x00007FFA537B513B+99] (c:\ci\python_1572550317365\work\python\pythonrun.c:85)
pymain_run_file [0x00007FFA5370137B+191] (c:\ci\python_1572550317365\work\modules\main.c:433)
pymain_run_filename [0x00007FFA53701423+111] (c:\ci\python_1572550317365\work\modules\main.c:1613)
pymain_run_python [0x00007FFA53670A24+390720] (c:\ci\python_1572550317365\work\modules\main.c:2873)
pymain_main [0x00007FFA536113A5+41] (c:\ci\python_1572550317365\work\modules\main.c:3415)
Py_Main [0x00007FFA53611052+82] (c:\ci\python_1572550317365\work\modules\main.c:3437)


问:
Create a repetitive image pattern using fabricjs
As the title says, I am trying to create a tile pattern by repeating the same image throughout my canvas element.

This is what I've tried so far: <canvas id='c' width='345' height='345'></canvas>

```<code>let canvas = new fabric.Canvas('c',{backgroundColor: "#fff"});
const logo = 'https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png';
canvas.add(
        new fabric.Line([7,10,17,10],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([10,10,10,150],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.IText("500mm",{
            left: 20,
            top: 152,
            fill: "grey",
            stroke: "grey",
            fontSize: 10,
            angle: 90
        }),
        new fabric.Line([10, 190, 10, 315], {
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([7,315,17,315],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([30,333,30,320],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([30,325,150,325],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.IText("380mm",{
            left: 152,
            top: 320,
            fill: "grey",
            stroke: "grey",
            fontSize: 10,
        }),
        new fabric.Line([187,325,310,325],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([310,333,310,320],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
    )
    fabric.Image.fromURL(logo, function(img) {
        var oImg = img.set({
            left: 40,
            top: 40,
            angle: 310
        }).scale(0.1);
        canvas.add(oImg);
    })
    canvas.renderTop();
</code>```

, but now I am stuck.

Here's a jsfiddle if it helps to visualize the problem faster: https://jsfiddle.net/1fevg8dc/3/

Any help in the right direction would help me greatly, as I really struggle with fabricjs's documentation.

My end goal would be to apply a greyscale filter on the image(declared as logo) and rotate the image at 45 degrees and create the pattern inside the lines that I've

答:
A tiled, repeated pattern as a fabric.js background is not that hard to do actually. However, the problem in your case is that you want it to be at an angle and a grayscale filter applied.

Anyway, first we need to create a canvas.js Shape object - which will serve as our background and hence needs to cover the whole viewport.

```<code>let shape = new fabric.Rect({
    width: canvas.width,
    height: canvas.height,
    left: 0,
    top: 0,
    selectable: false
});
</code>```

We don't add it to the stage yet though. As we want to fill the Shape with an image, we need to load it first. For this task we utilize the .fromURL() method of the Image object.

```<code>fabric.Image.fromURL("https://corsanywhere.herokuapp.com/https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png", function(img) {}, {crossOrigin: 'anonymous'})
</code>```

Inside the empty callback function - function(img) {} - the following must happen:

Convert the image to grayscale

Use this image as a fill for the shape

Rotate the fill e.g. 45°

The first step is done using fabric.js built-in filters

```<code>img.filters.push(new fabric.Image.filters.Grayscale());
img.applyFilters();
</code>```

Step number two involves creating a Pattern object which is then applied to the Shape object.

The last step is the tricky part. A fill doesn't have a rotation property. Instead it's transformed by a transformation matrix using it's patternTransform property. This patternTransform is an array of 6 values which control the position, scale and skew. For a 45 degree rotation it has to be like this:

```<code>let angle = -45 * Math.PI / 180;
let transformMatrix=[Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0];
</code>```

Let's elaborate a bit on the transformation matrix. As I said, it contains six values. If we give
those a meaningful name it looks a bit like this:

```<code>matrix= [scaleX, skewY, skewX, scaleY, translateX, translateY];
</code>```

We can see that there is no value which controls the rotation. That's because in a matrix, a rotation
is a combination of skew and scale. If we look back at our own transformation:

```<code>let transformMatrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0];
</code>```

it's indeed the scaleX, skewY, skewX and scaleY properties being populated.

If we were to alter the scale of a matrix, everything we would need to change it's scaleX and scaleY
properties. In this case however it's a bit different as we already applied a rotation. Fortunately
it ain't that hard. The scale itself is a decimal number, where 1 means no change, 2 is the double scale
and 0.5 is half the scale for example. So if we want to make the pattern half it's original size, we
need to multiply scaleX, skewY, skewX and scaleY by 0.5.

```<code>let angle = -45 * Math.PI / 180;
let scale = 0.5;
let transformMatrix = [Math.cos(angle) * scale, Math.sin(angle) * scale, -Math.sin(angle) * scale, Math.cos(angle) * scale, 0, 0];
</code>```

Now if we put everything together we will come up with this:

let canvas = this.__canvas = new fabric.Canvas('c');

let shape = new fabric.Rect({
  width: canvas.width,
  height: canvas.height,
  left: 0,
  top: 0,
  selectable: false
});

fabric.Image.fromURL("https://corsanywhere.herokuapp.com/https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png", function(img) {
  img.filters.push(new fabric.Image.filters.Grayscale());
  img.applyFilters();

  let angle = -45 * Math.PI / 180;
  let scale = 0.5;
  shape.set('fill', new fabric.Pattern({
    source: img._element,
    repeat: 'repeat',
    patternTransform: [Math.cos(angle) * scale, Math.sin(angle) * scale, -Math.sin(angle) * scale, Math.cos(angle) * scale, 0, 0]
  }));

  canvas.add(shape);
  canvas.renderAll();

}, {
  crossOrigin: 'anonymous'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js" integrity="sha512-ft2xOUYF7h2UeYQUbol4GJHrkGPVrgimINEYwLI23hyxN1JIy6EEj2vEc8RWWIIExvUKZvYq3oJTDrbif2oSVw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id="c" width="800" height="600" style="border:1px solid #ccc"></canvas></code>```

Body:
As the title says, I am trying to create a tile pattern by repeating the same image throughout my canvas element.

This is what I've tried so far: <canvas id='c' width='345' height='345'></canvas>

let canvas = new fabric.Canvas('c',{backgroundColor: "#fff"});
const logo = 'https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png';
canvas.add(
        new fabric.Line([7,10,17,10],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([10,10,10,150],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.IText("500mm",{
            left: 20,
            top: 152,
            fill: "grey",
            stroke: "grey",
            fontSize: 10,
            angle: 90
        }),
        new fabric.Line([10, 190, 10, 315], {
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([7,315,17,315],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([30,333,30,320],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([30,325,150,325],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.IText("380mm",{
            left: 152,
            top: 320,
            fill: "grey",
            stroke: "grey",
            fontSize: 10,
        }),
        new fabric.Line([187,325,310,325],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
        new fabric.Line([310,333,310,320],{
            fill: "grey",
            stroke: "grey",
            strokeWidth: 3
        }),
    )
    fabric.Image.fromURL(logo, function(img) {
        var oImg = img.set({
            left: 40,
            top: 40,
            angle: 310
        }).scale(0.1);
        canvas.add(oImg);
    })
    canvas.renderTop();

, but now I am stuck.

Here's a jsfiddle if it helps to visualize the problem faster: https://jsfiddle.net/1fevg8dc/3/

Any help in the right direction would help me greatly, as I really struggle with fabricjs's documentation.

My end goal would be to apply a greyscale filter on the image(declared as logo) and rotate the image at 45 degrees and create the pattern inside the lines that I've

Body:
A tiled, repeated pattern as a fabric.js background is not that hard to do actually. However, the problem in your case is that you want it to be at an angle and a grayscale filter applied.

Anyway, first we need to create a canvas.js Shape object - which will serve as our background and hence needs to cover the whole viewport.

let shape = new fabric.Rect({
    width: canvas.width,
    height: canvas.height,
    left: 0,
    top: 0,
    selectable: false
});

We don't add it to the stage yet though. As we want to fill the Shape with an image, we need to load it first. For this task we utilize the .fromURL() method of the Image object.

fabric.Image.fromURL("https://corsanywhere.herokuapp.com/https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png", function(img) {}, {crossOrigin: 'anonymous'})

Inside the empty callback function - function(img) {} - the following must happen:

Convert the image to grayscale

Use this image as a fill for the shape

Rotate the fill e.g. 45°

The first step is done using fabric.js built-in filters

img.filters.push(new fabric.Image.filters.Grayscale());
img.applyFilters();

Step number two involves creating a Pattern object which is then applied to the Shape object.

The last step is the tricky part. A fill doesn't have a rotation property. Instead it's transformed by a transformation matrix using it's patternTransform property. This patternTransform is an array of 6 values which control the position, scale and skew. For a 45 degree rotation it has to be like this:

let angle = -45 * Math.PI / 180;
let transformMatrix=[Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0];

Let's elaborate a bit on the transformation matrix. As I said, it contains six values. If we give
those a meaningful name it looks a bit like this:

matrix= [scaleX, skewY, skewX, scaleY, translateX, translateY];

We can see that there is no value which controls the rotation. That's because in a matrix, a rotation
is a combination of skew and scale. If we look back at our own transformation:

let transformMatrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0];

it's indeed the scaleX, skewY, skewX and scaleY properties being populated.

If we were to alter the scale of a matrix, everything we would need to change it's scaleX and scaleY
properties. In this case however it's a bit different as we already applied a rotation. Fortunately
it ain't that hard. The scale itself is a decimal number, where 1 means no change, 2 is the double scale
and 0.5 is half the scale for example. So if we want to make the pattern half it's original size, we
need to multiply scaleX, skewY, skewX and scaleY by 0.5.

let angle = -45 * Math.PI / 180;
let scale = 0.5;
let transformMatrix = [Math.cos(angle) * scale, Math.sin(angle) * scale, -Math.sin(angle) * scale, Math.cos(angle) * scale, 0, 0];

Now if we put everything together we will come up with this:

let canvas = this.__canvas = new fabric.Canvas('c');

let shape = new fabric.Rect({
  width: canvas.width,
  height: canvas.height,
  left: 0,
  top: 0,
  selectable: false
});

fabric.Image.fromURL("https://corsanywhere.herokuapp.com/https://www.logomaker.com/wpstatic/uploads/2018/11/bakerylogo2.png", function(img) {
  img.filters.push(new fabric.Image.filters.Grayscale());
  img.applyFilters();

  let angle = -45 * Math.PI / 180;
  let scale = 0.5;
  shape.set('fill', new fabric.Pattern({
    source: img._element,
    repeat: 'repeat',
    patternTransform: [Math.cos(angle) * scale, Math.sin(angle) * scale, -Math.sin(angle) * scale, Math.cos(angle) * scale, 0, 0]
  }));

  canvas.add(shape);
  canvas.renderAll();

}, {
  crossOrigin: 'anonymous'
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/500/fabric.min.js" integrity="sha512-ft2xOUYF7h2UeYQUbol4GJHrkGPVrgimINEYwLI23hyxN1JIy6EEj2vEc8RWWIIExvUKZvYq3oJTDrbif2oSVw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id="c" width="800" height="600" style="border:1px solid #ccc"></canvas>


问:
How to bypass CORS policy when sending get/post request from React JS?
From my React JS app , I need to fetch data from servers in other domains.
However, I am prevented by CORS policy and not able to fetch the data.

Let us assume that my React app is running on localhost:3000 during the development.
I want to make get/post call to another server running on  http://myserver.com
The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz

I have installed http-proxy-middleware thru npm and using it in my react app.
Created a setupProxy.js file under src folder with below content :

```<code>const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
   app.use(
      createProxyMiddleware('/data/records' , {
        target:'http://ext-server.com',
        changeOrigin: true
     })
 )
}
</code>```

On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com

```<code>getTheData() {

let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);

axios.get(url,
  {
    headers: {
     "Content-Type":"application/json;charset=UTL-8",
     "Access-Control-Allow-Origin": "*",
     Accept: "application/json",
      },
      baseURL: 'http://ext-server.com'
   }
 ).then((response) => {
     console.log(response["access_token"]);
  }).catch(error) => {
       console.log("Error: ", error)
  }).then(function () {
       console.log("always call it")
});

}
</code>```

In the package.json , I have added :

```<code>"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",
</code>```

But I am still getting below error:
Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.

Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware?
Any help will be very useful!
Thanks

答: As you can see from MDN the "Access-Control-Allow-Origin": "*" header is a response type header, this means that it should go to in your server response. Also I advise you to not use the * symbol, instead I would rather match it with the origin header in your Request.

Body:
From my React JS app , I need to fetch data from servers in other domains.
However, I am prevented by CORS policy and not able to fetch the data.

Let us assume that my React app is running on localhost:3000 during the development.
I want to make get/post call to another server running on  http://myserver.com
The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz

I have installed http-proxy-middleware thru npm and using it in my react app.
Created a setupProxy.js file under src folder with below content :

const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
   app.use(
      createProxyMiddleware('/data/records' , {
        target:'http://ext-server.com',
        changeOrigin: true
     })
 )
}

On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com

getTheData() {

let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);

axios.get(url,
  {
    headers: {
     "Content-Type":"application/json;charset=UTL-8",
     "Access-Control-Allow-Origin": "*",
     Accept: "application/json",
      },
      baseURL: 'http://ext-server.com'
   }
 ).then((response) => {
     console.log(response["access_token"]);
  }).catch(error) => {
       console.log("Error: ", error)
  }).then(function () {
       console.log("always call it")
});

}

In the package.json , I have added :

"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",

But I am still getting below error:
Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.

Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware?
Any help will be very useful!
Thanks


问:
Hibernate: Need to save the same object twice within the transaction
I need to save the same object twice within transaction, but hibernate always have only one sql update, any way to do it?
Here is the code:

```<code>....
session.beginTransaction();
Student s = session.get(Student.class, id);

// (1) first save
s.setSequenceNum(10);
session.saveOrUpdate(s);

// (2) second save
s.setSequenceNum(9);
session.saveOrUpdate(s);  // save again

session.getTransaction().commit();
session.close();
</code>```

hibernate will ignore the first one, and only have one sql update for the second. How can i let hibernate do both of the two sql update? I need this because it is the requirement in our project.

答:
saveOrUpdate is completely unnecessary for an attached instance. Hibernate will automatically persist the state of an attached object

at the end of the transaction

when executing a query whose result might depend on the new state of the object

when calling flush explicitely on the session

An attached object is an object that you have retrieved from the session (from a call to get, load, or from a query), or that you have made persistent via persist, save, update or merge (in this latter case, the passed object is not attached, but the returned object is).

Then why is saveOrUpdate useful? It's useful to make a transient or detached object persistent, i.e. an object which is not attached to a session, either because it's new, or because it was attached previously, but became detached when the session closed.

The idea of Hibernate is to flush the modified state (i.e. to execute an update SQL query) only when it's necessary, at the latest possible time. This way, it can avoid unnecessary updates and thus make the code more efficient. Your first update is unnecessary, unless you're doing a native SQL query in the same transaction between the two updates. Why would you want the intermediate state to be persisted?

Body:
I need to save the same object twice within transaction, but hibernate always have only one sql update, any way to do it?
Here is the code:

....
session.beginTransaction();
Student s = session.get(Student.class, id);

// (1) first save
s.setSequenceNum(10);
session.saveOrUpdate(s);

// (2) second save
s.setSequenceNum(9);
session.saveOrUpdate(s);  // save again

session.getTransaction().commit();
session.close();

hibernate will ignore the first one, and only have one sql update for the second. How can i let hibernate do both of the two sql update? I need this because it is the requirement in our project.


问:
django connect remote postgresql
Trying to connect to a remote server, serving my posgresql

My settings.py

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': 'ubuntu@username.host.com',
        'PORT': '5432',
    }
}
</code>```

Getting error:

```<code>django.db.utils.OperationalError: could not translate host name "ubuntu@hostname.host.com" to address: Name or service not known

</code>```

Where the hostname and host is of course not hostname and host, just using for this example.

答:
For the host, you have to pass the ip address or the domain name of your postgresql host instance.

```<code>'HOST': 'host.com'
</code>```

or

```<code>'HOST': '<ip_address>'
</code>```

Title: django connect remote postgresql

Body:
Trying to connect to a remote server, serving my posgresql

My settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': 'ubuntu@username.host.com',
        'PORT': '5432',
    }
}

Getting error:

django.db.utils.OperationalError: could not translate host name "ubuntu@hostname.host.com" to address: Name or service not known

Where the hostname and host is of course not hostname and host, just using for this example.

Body:
For the host, you have to pass the ip address or the domain name of your postgresql host instance.

'HOST': 'host.com'

or

'HOST': '<ip_address>'