build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method in a number of different situations. For example:

This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor, the given BuildContext, and the internal state of this State object.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

Design discussion

Why is the build method on State, and not StatefulWidget?

Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.

For example, AnimatedWidget is a subclass of StatefulWidget that introduces an abstract Widget build(BuildContext context) method for its subclasses to implement. If StatefulWidget already had a build method that took a State argument, AnimatedWidget would be forced to provide its State object to subclasses even though its State object is an internal implementation detail of AnimatedWidget.

Conceptually, StatelessWidget could also be implemented as a subclass of StatefulWidget in a similar manner. If the build method were on StatefulWidget rather than State, that would not be possible anymore.

Putting the build function on State rather than StatefulWidget also helps avoid a category of bugs related to closures implicitly capturing this. If you defined a closure in a build function on a StatefulWidget, that closure would implicitly capture this, which is the current widget instance, and would have the (immutable) fields of that instance in scope:

// (this is not valid Flutter code)
class MyButton extends StatefulWidgetX {
  MyButton({super.key, required this.color});

  final Color color;

  @override
  Widget build(BuildContext context, State state) {
    return SpecialWidget(
      handler: () { print('color: $color'); },
    );
  }
}

For example, suppose the parent builds MyButton with color being blue, the $color in the print function refers to blue, as expected. Now, suppose the parent rebuilds MyButton with green. The closure created by the first build still implicitly refers to the original widget and the $color still prints blue even through the widget has been updated to green; should that closure outlive its widget, it would print outdated information.

In contrast, with the build function on the State object, closures created during build implicitly capture the State instance instead of the widget instance:

class MyButton extends StatefulWidget {
  const MyButton({super.key, this.color = Colors.teal});

  final Color color;
  // ...
}

class MyButtonState extends State<MyButton> {
  // ...
  @override
  Widget build(BuildContext context) {
    return SpecialWidget(
      handler: () { print('color: ${widget.color}'); },
    );
  }
}

Now when the parent rebuilds MyButton with green, the closure created by the first build still refers to State object, which is preserved across rebuilds, but the framework has updated that State object's widget property to refer to the new MyButton instance and ${widget.color} prints green, as expected.

See also:

  • StatefulWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  readJson();
  // backpress confirmation dialog
  Future<bool> _onBackPressed() {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => new AlertDialog(
        title: new Text(
          'Confirm Cancellation',
          style: new TextStyle(fontFamily: 'OpenSans'),
        ),
        content: new Text(
          'Are you sure you want to cancel the verification process?',
          style: new TextStyle(fontFamily: 'OpenSans'),
        ),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: new GestureDetector(
              onTap: () => Navigator.of(context).pop(false),
              child: Text(
                "Not Now",
                style: new TextStyle(
                    fontSize: 13.w,
                    color: Color(0xff2b6ad8),
                    fontFamily: 'OpenSans'),
              ),
            ),
          ),
          SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: new GestureDetector(
              onTap: () => {
                isCheck = false,
                indexTempList = [],
                verificationTypeList = [],
                isPayloadSet = false,
                supportedTypes_list = [],
                Navigator.pushAndRemoveUntil(
                    context,
                    MaterialPageRoute(builder: (context) => userHome),
                        (route) => false),
                widget.callback(verificatonCancel),
              },
              child: Text(
                "Confirm",
                style: new TextStyle(
                    fontSize: 13.w,
                    color: Color(0xff2b6ad8),
                    fontFamily: 'OpenSans'),
              ),
            ),
          ),
        ],
      ),
    ).then((value) => value ?? false);
  }

  // show dialog if internet connectivity is lost
  Future<dynamic> internetDialog() {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => new AlertDialog(
        title: new Text(
          'Internet Disconnect.',
          style: new TextStyle(fontFamily: 'OpenSans'),
        ),
        content: new Text(
          'Internet is not availabe. Connect internet to proceed.',
          style: new TextStyle(fontFamily: 'OpenSans'),
        ),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: new GestureDetector(
              onTap: () => Navigator.of(context).pop(false),
              child: Text(
                "Cancel",
                style: new TextStyle(fontFamily: 'OpenSans'),
              ),
            ),
          ),
          SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: new GestureDetector(
              onTap: () {
                AppSettings.openWIFISettings();
                Navigator.pushAndRemoveUntil(
                    context,
                    MaterialPageRoute(builder: (context) => userHome),
                        (route) => false);
              },
              child: Text(
                "OK",
                style: new TextStyle(fontFamily: 'OpenSans'),
              ),
            ),
          ),
        ],
      ),
    ) .then((value) => value ?? false);
  }

  if (!isPayloadSet) {
    isPayloadSet = true;
    requestedPayload = shufti_pro();
  }

  //Open webview in offiste verification
  if ((requestedPayload.containsKey("open_webView") &&
      requestedPayload["open_webView"] == true) ||
      (!requestedPayload.containsKey("face") &&
          !requestedPayload.containsKey("document") &&
          !requestedPayload.containsKey("document_two") &&
          !requestedPayload.containsKey("address") &&
          !requestedPayload.containsKey("consent") &&
          (requestedPayload.containsKey("background_checks") ||
              requestedPayload.containsKey("phone")))) {
    check().then((intenet) {
      if (intenet != null && intenet) {
        ApiMethods().apiRequest().then((value) async {
          if (!isWebViewOpened) {
            isWebViewOpened = true;
            isPayloadSet = false;
            if (value.contains("verification_url")) {
              final onsite_response = json.decode(value);

              if (await Permission.camera.request().isGranted &&
                  await Permission.microphone.request().isGranted) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => Onsite(
                        onsite_response['verification_url'].toString(),
                        callback: (res) {
                          widget.callback(res);
                          print("\n\ncalling preview: " + res.toString());
                        }, title: '',
                      )),
                );
              } else {
                // You can request multiple permissions at once.
                Map<Permission, PermissionStatus> statuses = await [
                  Permission.camera,
                  Permission.microphone,
                ].request();
              }
            } else {
              widget.callback(value);
              Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(builder: (context) => userHome),
                      (route) => false);
            }
          }
        });
      } else {
        internetDialog();
      }
    });

    // ApiMethods().statusApiRequest().then((value) async {
    //   print("\n\n\n hehehe: " + value.toString() + "\n\n");
    // });
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "assets/sdk/Preload_Animation.gif",
                height: 100.h,
                width: 0.4.sw,
              ),
              Padding(
                padding: EdgeInsets.only(
                  top: 25.w,
                  left: 25.w,
                  bottom: 5.w,
                  right: 25.w,
                ),
                child: Container(
                  child: Center(
                    child: Text(
                      "Opening WebView..",
                      style: TextStyle(fontFamily: 'OpenSans', fontSize: 17.sp),
                    ),
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(
                  top: 1.w,
                  left: 25.w,
                  bottom: 5.w,
                  right: 25.w,
                ),
                child: Container(
                  child: Center(
                    child: Text(
                      "Please Wait...",
                      style: TextStyle(
                          fontFamily: 'OpenSans',
                          fontSize: 18.sp,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ),
            ],
          )),
    );
  }
  else {
    // Offsite verification
    // show consent screen id show consent parameter is 1
    if (requestedPayload["show_consent"] == 1) {
      return ScreenUtilInit(
          builder: () => WillPopScope(
            onWillPop: _onBackPressed,
            child: Scaffold(
              backgroundColor: Colors.white,
              body: Center(
                child: Column(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(
                        top: 30.w,
                      ),
                      child: Container(
                        height: 50.h,
                        width: 1.sw,
                        alignment: Alignment.center,
                        child: new Text(
                          "Declaration of Consent",
                          style: new TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                            fontFamily: 'OpenSans',
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        top: 10.w,
                        left: 20.w,
                        bottom: 5.w,
                        right: 20.w,
                      ),
                      child: Container(
                        alignment: Alignment.topLeft,
                        child: new Text(
                          "Help us verify your\nidentity",
                          style: new TextStyle(
                            fontSize: 24.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                            fontFamily: 'OpenSans',
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        top: 5.w,
                        left: 18.w,
                        bottom: 5.w,
                        right: 18.w,
                      ),
                      child: Container(
                        alignment: Alignment.topLeft,
                        child: new Text(
                          "Identity Verification Consent",
                          style: new TextStyle(
                            fontSize: 17.sp,
                            fontWeight: FontWeight.normal,
                            color: Colors.black,
                            fontFamily: 'OpenSans',
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 220.h,
                      width: 1.sw,
                      child: Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(
                            top: 7.w,
                            left: 18.w,
                            bottom: 5.w,
                            right: 18.w,
                          ),
                          child: SingleChildScrollView(
                            scrollDirection: Axis.vertical,
                            child: Container(
                              alignment: Alignment.topLeft,
                              child: new Text(
                                "I declare that I am at least 16 years of age; I agree to the collection, processing or storage"
                                    " of my personal information by Shufti Pro for the purpose(s) of identity verification; that the information"
                                    " I provide is true and accurate to the best of my knowledge; and I shall be fully responsible in case I provide"
                                    " wrong information or any of the documents I use are fake, forged, counterfeit, etc.",
                                style: new TextStyle(
                                  fontSize: 14.5.sp,
                                  fontWeight: FontWeight.normal,
                                  color: Colors.black,
                                  fontFamily: 'OpenSans',
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                        child: Row(
                          children: <Widget>[
                            Container(
                              child: Checkbox(
                                value: isCheck,
                                onChanged: ConsentChk,
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                bottom: 5.w,
                              ),
                              child: Container(
                                width: 0.85.sw,
                                alignment: Alignment.topLeft,
                                child: RichText(
                                  text: new TextSpan(
                                    children: [
                                      new TextSpan(
                                        text:
                                        "I agree to the above statement, and I have read the ",
                                        style: new TextStyle(
                                          fontSize: 14.5.sp,
                                          fontWeight: FontWeight.normal,
                                          color: Colors.black,
                                          fontFamily: 'OpenSans',
                                        ),
                                      ),
                                      new TextSpan(
                                        text: 'Privacy Policy',
                                        style: new TextStyle(
                                          fontSize: 14.5.sp,
                                          fontWeight: FontWeight.normal,
                                          decoration:
                                          TextDecoration.underline,
                                          color: Colors.blue,
                                          fontFamily: 'OpenSans',
                                        ),
                                        recognizer: new TapGestureRecognizer()
                                          ..onTap = () {
                                            launch(
                                                'https://shuftipro.com/privacy-policy');
                                          },
                                      ),
                                      new TextSpan(
                                        text:
                                        " of Shufti Pro.",
                                        style: new TextStyle(
                                          fontSize: 14.5.sp,
                                          fontWeight: FontWeight.normal,
                                          color: Colors.black,
                                          fontFamily: 'OpenSans',
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        )),
                    Spacer(),
                    Padding(
                      padding: EdgeInsets.only(
                        top: 7.w,
                        left: 10.w,
                        bottom: 5.w,
                        right: 10.w,
                      ),
                      child: Container(
                        height: 45.h,
                        width: 1.sw,
                        child: RaisedButton(
                          onPressed: isCheck
                              ? () => Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder:
                                    (context) => ShowInstructions(
                                  callback: (res) {
                                    widget.callback(res);
                                    print("\n\ncalling preview: " +
                                        res.toString());
                                  },
                                )),
                          )
                              : null,
                          textColor: Colors.white,
                          color: Color(0xff2b6ad8),
                          child: new Container(
                            margin: const EdgeInsets.fromLTRB(5, 0, 0, 0),
                            child: new Text(
                              "Yes, Continue",
                              textAlign: TextAlign.center,
                              style: new TextStyle(
                                fontSize: 17.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                                fontFamily: 'OpenSans',
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        left: 10.w,
                        right: 10.w,
                      ),
                      child: Container(
                        height: 45.h,
                        width: 1.sw,
                        child: OutlinedButton(
                          onPressed: () {
                            _onBackPressed();
                          },
                          style: OutlinedButton.styleFrom(
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5)),
                          ),
                          child: new Container(
                            margin: const EdgeInsets.fromLTRB(5, 0, 0, 0),
                            child: new Text(
                              "No, Cancel",
                              textAlign: TextAlign.center,
                              style: new TextStyle(
                                fontSize: 17.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.black,
                                fontFamily: 'OpenSans',
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Spacer(),
                    Container(
                        height: 13.h,
                        child:
                        Image.asset("assets/images/footerImage.png")),
                  ],
                ),
              ),
            ),
          ));
    } else {
      // show instructions screen if show consent is 0
      WidgetsBinding.instance?.addPostFrameCallback((_) {
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => ShowInstructions(
                callback: (res) {
                  widget.callback(res);
                  print("\n\ncalling preview: " + res.toString());
                },
              )),
        );
      });

      return Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: Text(
            "Opening Web..",
            style: TextStyle(
              fontFamily: 'OpenSans',
            ),
          ),
        ),
      );
    }
  }
}