Home > Enterprise >  The argument type 'Future<Widget>' can't be assigned to the parameter type 
The argument type 'Future<Widget>' can't be assigned to the parameter type 

Time:12-10

import 'dart:async';
import 'package:data_connection_checker/data_connection_checker.dart';
import 'package:flutter/material.dart';
import 'package:nartaqi/no_connection_page.dart';
import 'package:nartaqi/notifications.dart';
import 'body.dart';
import 'constants.dart';

class HomePage extends StatefulWidget {
   const HomePage({
    Key? key,
  }) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {

  StreamSubscription<DataConnectionStatus>? listener;

  Future<Widget> buildBody() async{
    DataConnectionStatus status = await checkInternet();
    if(status == DataConnectionStatus.connected){
      return Body();
    }else{
      return NoConnectionPage();
    }
  }

  @override
  void dispose() {
    listener?.cancel();
    super.dispose();
  }
  checkInternet()async{
    print("The statement 'this machine is connected to the Internet' is: ");
    print(await DataConnectionChecker().hasConnection);
    // returns a bool

    // We can also get an enum value instead of a bool
    print("Current status: ${await DataConnectionChecker().connectionStatus}");
    // prints either DataConnectionStatus.connected
    // or DataConnectionStatus.disconnected

    // This returns the last results from the last call
    // to either hasConnection or connectionStatus
    print("Last results: ${DataConnectionChecker().lastTryResults}");

    // actively listen for status updates
    // this will cause DataConnectionChecker to check periodically
    // with the interval specified in DataConnectionChecker().checkInterval
    // until listener.cancel() is called
    listener = DataConnectionChecker().onStatusChange.listen((status) {
      switch (status) {
        case DataConnectionStatus.connected:
          print('Data connection is available.');
          break;
        case DataConnectionStatus.disconnected:
          print('You are disconnected from the internet.');
          break;
      }
    });

    // close listener after 30 seconds, so the program doesn't run foreverawait listener.cancel();
    return await DataConnectionChecker().connectionStatus;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: kPrimaryColor,
        elevation: 0.0,
        leading: IconButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const NotificationPage(),),);
          },
          icon: const Icon(
            Icons.notifications,
            color: Color(0xFFF9A826),
          ),
        ),
        actions: const [
          Padding(
            padding:
            EdgeInsets.symmetric(horizontal: 10.0, vertical: 16.0),
            child: Text(
              'الرئيسية',
              style: kHomeScreenTextStyle,
            ),
          ),
        ],
      ),
      body:  buildBody(),
    );
  }

}

I'm trying to connect my app to the internet by using data_connection_checker, i followed a video making it this way, but i get this error, what should i do? also if it is possible for another way to check for internet connection actual internet access not network detection of WiFi or mobile, using a ping method or another flutter package will be helpful

CodePudding user response:

buildBody() is future method, use FutureBuilder for this.

 body: FutureBuilder<Widget>(
        future: buildBody(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData) {
            return snapshot.data!;
          } else {
            /// you handle others state like error while it will a widget no matter what, you can skip it
            return CircularProgressIndicator();
          }
        },
      ),

CodePudding user response:

body in Scaffold requires a Widget but you are sending it a Future widget buildBody(). Instead try sending

body: await buildBody()

CodePudding user response:

Please refer to below code

Widget buildBody() {
    checkInternet().then((status) {
      if (status == DataConnectionStatus.connected) {
        return Body();
      } else {
        return NoConnectionPage();
      }
    });
  }

body: buildBody(),
  • Related