Can anyone help me to disable a elevated button in my flutter app?

88 views Asked by At

I'm attempting to disable the elevated "Scan Devices" button while the scanning process is in progress. When I alter its state after pressing the button, it does not return to its active state, even after the scanning is finished.

Here is my code :



import 'package:flutter/material.dart';
import 'package:lan_scanner/lan_scanner.dart';
import 'package:wifi/wifi.dart';
import 'package:easy_loading_button/easy_loading_button.dart';

void main() =\> runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'LAN Scanner',
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
\_MyHomePageState createState() =\> \_MyHomePageState();
}

class \_MyHomePageState extends State\<MyHomePage\> {
List\<String\> \_ips = \[\];
var \_isScanning = false; // add this variable to keep track of scanning status

void \_scanDevices() async {
if (\_isScanning == true) {
return; // if scanning is already ongoing, return immediately
} else {
setState(
() =\> \_isScanning = true,
);
}
\_ips.clear();
// Get wifi IP and subnet
final String ip = await Wifi.ip;
final String subnet = ip.substring(0, ip.lastIndexOf('.'));
final scanner = LanScanner(debugLogging: true);

    final stream = scanner.icmpScan(subnet);
    
    stream.listen((HostModel host) {
      if (host.ip != null) {
        setState(() {
          _ips.add(host.ip!);
        });
      }
    }).onDone(() {
      setState(() => _isScanning = false);
    });

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('LAN Scanner'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: \<Widget\>\[
ElevatedButton(
onPressed: \_isScanning
? null
: \_scanDevices, // disable the button if scanning is ongoing
child: const Text('Scan Devices'),
),
const SizedBox(height: 20.0),
const Text(
'Devices Found:',
style: TextStyle(fontSize: 20.0),
),
const SizedBox(height: 10.0),
Expanded(
child: \_ips.isEmpty
? const Text('No devices found.')
: ListView.builder(
itemCount: \_ips.length,
itemBuilder: (context, index) {
final ip = \_ips\[index\];
return ListTile(
title: Text(ip),
);
},
),
),
\],
),
),
);
}
}

/* Can anyone shed some light on this matter? I'm totally new to flutter.

The button needs to get disabled when the scan is running and re-enable after it's done.

1

There are 1 answers

0
Nikhith sunil On

try to update _isScanning to false from inside listen()