为Flutter手电筒创建开关图标

huangapple go评论59阅读模式
英文:

create on off toggle Icon for flutter torch

问题

我尝试在我的Flutter应用程序中实现使用手机闪光灯作为手电筒的可能性。开关按钮位于应用栏中。这一切都运行良好,除了开灯和关灯按钮同时出现。我该如何做到只显示其中一个,具体取决于灯是否打开或关闭?
非常感谢您的帮助。
我使用了flutter torch_light: ^0.4.0

Class TorchController extends StatelessWidget {
  const TorchController({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: FutureBuilder<bool>(
        future: _isTorchAvailable(context),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData && snapshot.data!) {
            return Column(
              children: [
                Expanded(
                  child: Center(
                    child: IconButton ( icon: const Icon(Icons.flashlight_on_outlined,size: 35,),


                      onPressed: () async {
                        _enableTorch(context);
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Center(
                    child: IconButton (icon: const Icon(Icons.flashlight_off_outlined,size: 35,),


                      onPressed: () async {
                        _disableTorch(context);
                      },
                    ),
                  ),
                ),
              ],
            );
          } else if (snapshot.hasData) {
            return const Center(
              child: Text('没有可用的手电筒。'),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }

 Future<bool> _isTorchAvailable(BuildContext context) async {
   try {
    return await TorchLight.isTorchAvailable();
    } on Exception catch (_) {
      _showMessage(
        '无法检查设备是否有可用的手电筒',
       context,
      );
      rethrow;
    }
  }

  Future<void> _enableTorch(BuildContext context) async {
    try {
      await TorchLight.enableTorch();
    } on Exception catch (_) {
      _showMessage('无法启用手电筒', context);
    }
  }

  Future<void> _disableTorch(BuildContext context) async {
    try {
      await TorchLight.disableTorch();
    } on Exception catch (_) {
      _showMessage('无法关闭手电筒', context);
    }
  }

  void _showMessage(String message, BuildContext context) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }
}
// 结束

请注意,我已经翻译了代码部分,如您所要求,不包括翻译代码部分。

英文:

I tried to implement the possibility to use the flash of the phone as a torch in my flutter app. The on/ off button is located in the appbar. This runs fine except the light on and light off Button appear both at the same time. How can I make it, that either one or the other is shown. depending on whether the lamp is on or off?
Thank you very much for your help
I used the flutter torch_light: ^0.4.0


Class TorchController extends StatelessWidget {
const TorchController({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder&lt;bool&gt;(
future: _isTorchAvailable(context),
builder: (BuildContext context, AsyncSnapshot&lt;bool&gt; snapshot) {
if (snapshot.hasData &amp;&amp; snapshot.data!) {
return Column(
children: [
Expanded(
child: Center(
child: IconButton ( icon: const Icon(Icons.flashlight_on_outlined,size: 35,),
onPressed: () async {
_enableTorch(context);
},
),
),
),
Expanded(
child: Center(
child: IconButton (icon: const Icon(Icons.flashlight_off_outlined,size: 35,),
onPressed: () async {
_disableTorch(context);
},
),
),
),
],
);
} else if (snapshot.hasData) {
return const Center(
child: Text(&#39;No torch available.&#39;),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Future&lt;bool&gt; _isTorchAvailable(BuildContext context) async {
try {
return await TorchLight.isTorchAvailable();
} on Exception catch (_) {
_showMessage(
&#39;Could not check if the device has an available torch&#39;,
context,
);
rethrow;
}
}
Future&lt;void&gt; _enableTorch(BuildContext context) async {
try {
await TorchLight.enableTorch();
} on Exception catch (_) {
_showMessage(&#39;Could not enable torch&#39;, context);
}
}
Future&lt;void&gt; _disableTorch(BuildContext context) async {
try {
await TorchLight.disableTorch();
} on Exception catch (_) {
_showMessage(&#39;Could not disable torch&#39;, context);
}
}
void _showMessage(String message, BuildContext context) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
}
}
//Ende```
</details>
# 答案1
**得分**: 1
首先,将小部件从`stateless`更改为`stateful`小部件。然后
1. 定义一个变量来显示手电筒的状态
- isTorchOn = false;
2. 在`_enableTorch()`中将该值更新为`true`
**(不需要传递上下文,因为它现在是一个有状态的小部件)**
```dart
Future<void> _enableTorch(BuildContext context) async {
try {
await TorchLight.enableTorch();
setState(() => isTorchOn = true);
} on Exception catch (_) {
_showMessage('无法启用手电筒', context);
}
}
  1. 对于_disableTorch()也要做同样的操作,将isTorchOn设置为false
Future<void> _disableTorch(BuildContext context) async {
    try {
        await TorchLight.disableTorch();
        setState(() => isTorchOn = false);
    } on Exception catch (_) {
        _showMessage('无法禁用手电筒', context);
    }
}

请注意,上述代码片段是在Dart编程语言中编写的,用于Flutter应用程序中的状态管理。

英文:

First of all, change the widget from stateless to stateful widget. Then

  1. define a variable to show the status of the torch
    • isTorchOn = false;
  2. on _enableTorch() update the value to true

(no need to pass context as it is now a stateful widget)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

Future&lt;void&gt; _enableTorch(BuildContext context) async {
try {
await TorchLight.enableTorch();
setState(()=&gt; isTorchOn = true);
} on Exception catch (_) {
_showMessage(&#39;Could not enable torch&#39;, context);
}
}

<!-- end snippet -->

  1. do the same for _disableTorch() as set isTorchOn to false

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

Future&lt;void&gt; _disableTorch(BuildContext context) async {
try {
await TorchLight.disableTorch();
setState(()=&gt; isTorchOn = false);
} on Exception catch (_) {
_showMessage(&#39;Could not disable torch&#39;, context);
}
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 20:36:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定